1004. Counting Leaves (30)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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 Input

2 1

01 1 02

Sample Output

0 1

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 100;
vector<int> children[maxn];
int level[maxn] = { 0 };
int nochild[maxn] = { 0 };
int N, M;
int layer;
void BFS(int root)
{
queue<int> Q;
Q.push(root);
int lastNode = root,newlastNode;
//level[root] = 1;
layer = 1;
while (!Q.empty())
{
int t = Q.front();
Q.pop();
if (children[t].size())
{
for (int i = 0; i < children[t].size(); i++)
{
Q.push(children[t][i]);
level[children[t][i]] = level[t] + 1;
}
newlastNode = children[t][children[t].size() - 1];
}
else
nochild[layer]++;
if (t == lastNode)
{
lastNode = newlastNode;
layer++;
}

}
}
int hashtable[maxn] = { 0 };
int main()
{
scanf("%d%d", &N, &M);
int father, k, child;
for (int i = 0; i < M; i++)
{
scanf("%d %d", &father, &k);
for (int j = 0; j < k; j++)
{
scanf("%d", &child);
children[father].push_back(child);
}
}
BFS(1);
for (int i = 1; i <layer; i++)
{
if(i==1)
printf("%d", nochild[i]);
else
printf(" %d", nochild[i]);
}
return 0;
}