C++程式碼:求解n天后樹的高度


假設我們有一個包含n個元素的陣列A。A的元素要麼是0要麼是1。有一棵樹。在連續的n天裡,如果A[i]是0,則不澆水;如果A[i]是1,則澆水,花朵的生長方式如下:

  • 如果樹連續兩天不澆水,它就會枯死。

  • 如果在第i天澆水,它會生長1釐米。

  • 如果連續兩天(第i天和第i+1天)澆水,它會生長5釐米而不是1釐米。

  • 如果在第i天不澆水,它就不會生長。

一開始,樹高1釐米。我們需要找到n天后樹的高度。如果它死了,則返回-1。

因此,如果輸入類似於A = [0, 1, 1],則輸出將是7,因為第一天它不會生長,所以高度是1,第二天高度將是2,然後第三天它將是2 + 5 = 7。

步驟

為了解決這個問題,我們將遵循以下步驟:

r := 1
y := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   x := A[i]
   if r is same as -1, then:
      Ignore following part, skip to the next iteration
   if x is non-zero and y is non-zero, then:
      r := r + 5
   otherwise when x is non-zero, then:
      (increase r by 1)
   otherwise when not x is non-zero and not y is non-zero and i > 0, then:
      r := -1
   y := x
return r

示例

讓我們來看下面的實現來更好地理解:

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int r = 1;
   int y = 0;
   int n = A.size();
   for (int i = 0; i < n; ++i){
      int x = A[i];
      if (r == -1)
         continue;
      if (x && y)
         r += 5;
      else if (x)
         ++r;
      else if (!x && !y && i > 0)
         r = -1;
      y = x;
   }
   return r;
}
int main(){
   vector<int> A = { 0, 1, 1 };
   cout << solve(A) << endl;
}

輸入

{ 0, 1, 1 }

輸出

7

更新於:2022年3月15日

瀏覽量:169

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.