UVa 699 - The Falling Leaves
题意
先序输入一个带权二叉树, -1即无该儿子
思路
水题
递归输入, 用数组保存每个水平位置的总和即可
一开始没读清楚题, 以为是每一行作为一个二叉树, 本来想用string输入stringstream切割, 观察样例就能推翻
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <sstream>
using namespace std;
const int maxn = 100;
int s[maxn];
int minsize, maxsize;
void build(int,int);
void build( int i ){
int x;
cin >> x;
if( x == -1 ) return;
s[i] += x;
minsize = min(minsize, i);
maxsize = max(maxsize, i);
build(i-1);
build(i+1);
}
bool solve( int i ){
minsize = 101, maxsize = -1;
memset(s,0,sizeof(s));
int x;
cin >> x;
if( x == -1 ) return false;
s[i] += x;
build(i-1);
build(i+1);
minsize = min(minsize, i);
maxsize = max(maxsize, i);
}
int main()
{
int i, x;
int casenum = 0;
while( solve(maxn/2) ){
for( int j = minsize; j <= maxsize; j++ ){
if( j == minsize ) cout << "Case " << ++casenum << ':' << endl;
else cout << ' ';
cout << s[j];
}
cout << endl << endl;
}
return 0;
}