【紫书】 The Falling Leaves UVA - 699 递归得简单
题意:给你一颗二叉树的前序遍历,空子树以-1表示,将左右子树的权值投影到一维数轴上,左儿子位置为根位置-1,右儿子+1求个个整点上的和;
题解:递归,整个过程只需维护一个sum数组。
更新根,更新leftson ,更新rightson;
代码:
#define _CRT_SECURE_NO_WARNINGS #include "stdio.h" #include<stdio.h> #include<algorithm> #include<string> #include<vector> #include<list> #include<set> #include<iostream> #include<string.h> #include<queue> #include<string> #include<sstream> using namespace std; const int maxn = 80+5; int sum[maxn],p; void build(int p) {//更新以p为根的树对sum的贡献:更新根,更新leftson ,更新right son; 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"; } //system("pause"); return 0; }
成功的路并不拥挤,因为大部分人都在颓(笑)