Input
Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
Output
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line.
Sample Input2 1 01 1 02Sample Output
0 1
思路:首先定义树结构体,包含孩子结点个数和id,再加上一个层次信息,便于之后统计.用数组保存树,id作索引.这里考虑使用层次遍历来统计每层子结点数为零的结点.注意输入只含有根的情况.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TNode{
int n_child = 0;
int lvl;
vector<int> child;
};
int main()
{
int n,m,id;
cin>>n>>m;
TNode tree[100];
while(m--){
TNode node;
cin>>id>>node.n_child;
for(int i=0;i<node.n_child;++i){
int id_;
cin>>id_;
node.child.push_back(id_);
}
tree[id] = node;
}
if(tree[1].n_child==0){
cout<<'1';
return 0;
}
tree[1].lvl = 0;
queue<TNode> q;
int level[100] = {0};
bool flag[100] = {0};
q.push(tree[1]);
level[0] = 0;
while(!q.empty()){
TNode node = q.front();
q.pop();
flag[node.lvl] = 1;
for(int i=0;i<node.n_child;++i){
TNode &child_i = tree[node.child[i]];
child_i.lvl = node.lvl+1;
q.push(child_i);
if(child_i.n_child==0)
++level[child_i.lvl];
}
}
for(int i=0;i<100;++i){
if(!i)
cout<<level[0];
else if(flag[i])
cout<<' '<<level[i];
}
return 0;
}