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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP