题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19244
题意:给定一棵二叉树,把根节点标号成0,然后每往左走标号就减1,每往右走标号就加1,问相同标号的节点的值得和,按标号的大写依次输出
思路:输入挺坑的,不过看了一会,可以边输入边建树,碰到其他值要接着往下递归建树,碰到-1就不用递归了。判断是不是结束,只要判断根节点是否为空就可以了。建树的时候顺便给每个点标号,然后用map<int, int> 去映射标号与节点值和,最后依次输出就好
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
using namespace std;
const int N = 1100;
const int INF = 0x3f3f3f3f;
int cas = 0;
int a;
map<int, int> mpa;
struct node
{
int v, sign;
node *lc, *rc;
node(int v = 0, int sign = 0, node *lc = NULL, node *rc = NULL): v(v), sign(sign), lc(lc), rc(rc){}
};
void build(node* &root, int cnt)
{
scanf("%d", &a);
if(a == -1) return; //不用建当前节点,也不用往下递归了
root = new node(a, cnt);
build(root ->lc, cnt - 1);
build(root ->rc, cnt + 1);
}
void dfs(node *root)
{
if(root != NULL)
{
mpa[root->sign] += root ->v;
dfs(root ->lc);
dfs(root ->rc);
}
}
int main()
{
while(true)
{
node *root = NULL;
mpa.clear();
build(root, 0);
if(root == NULL) break; //根节点为空,结束
else
{
dfs(root);
printf("Case %d:\n", ++cas);
bool flag = false;
for(map<int, int> :: iterator p = mpa.begin(); p != mpa.end(); p++) //依次输出
{
if(! flag)
printf("%d", p ->second), flag = true;
else printf(" %d", p ->second);
}
printf("\n");
}
printf("\n");
}
return 0;
}