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
————————————————
这个题目,自己错的比较奇怪,主要是有一个8分的测试点二过不了,原因是
child 的level不一定为父亲的level+1,所以,在读取的时候不能简单的+1,因为你不知道输入的顺序,需要重新扫描一遍。
#include <iostream>
#include <queue>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAX 101
int fa[MAX]={0};
struct node
{
int child[MAX];
int k;
int level;
};
node tree[MAX];
int main(int argc, char** argv) {
int N,M;
cin>>N>>M;
for(int i=0; i<N; i++)
{
tree[i].k=0;
tree[i].level=0;
}
for(int i=0; i<M; i++)
{
int index=0;
cin>>index;
cin>>tree[index].k;
for(int j=0; j<tree[index].k; j++)
{
cin>>tree[index].child[j];
//tree[tree[index].child[j]].level=tree[index].level+1;//!!!!!不能简单的+1,因为输入的顺序
}
}
for(int i=1; i<N; i++)
{
for(int j=0; j<tree[i].k; j++)
tree[tree[i].child[j]].level=tree[i].level+1;
}
queue<int> q;
q.push(1);
int cnt=0,step=0;
while(!q.empty())
{
int u=q.front();q.pop();
int newstep=tree[u].level;
if(newstep != step)
{
printf("%d ",cnt);
cnt=0;
step=newstep;
}
if(tree[u].k == 0) cnt++;
for(int i=0; i<tree[u].k; i++)
{
q.push(tree[u].child[i]);
}
}
printf("%d",cnt);
return 0;
}