题目链接:https://vjudge.net/problem/UVA-699
题解:按题目要求读入数据的过程中,进行求和的计算,我在最开始的时候,想着用建树的方法来做,最后建树的过程中写错了,所以参考了一下书中代码。
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<memory>
using namespace std;
const int maxn = 1000010;
int sum[maxn];
void build(int p)
{
int v;
cin >> v;
if (v == -1)return;
sum[p] += v;
build(p - 1);
build(p + 1);
}
bool init()
{
int v;
cin >> v;
if (v == -1)return false;
memset(sum, 0, sizeof(sum));
int pos = maxn / 2;
sum[pos] = v;
build(pos - 1);
build(pos + 1);
}
int main() {
int kase = 0;
while (init()) {
int p = 0;
while (sum[p] == 0)p++;
cout << "Case: " << ++kase << ":\n" << sum[p++];
while (sum[p] != 0)cout << " " << sum[p++];
cout << "\n\n";
}
return 0;
}