Counting Leaves(PATA-1004)

题面

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

输入

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:

1ID 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.

The input ends with N being 0. That case must NOT be processed.

输出

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.

样例输入

12 1
201 1 02

样例输出

10 1

提示

思路

给你一棵树,求每一层叶子节点的个数。

开个数组保存,然后dfs一下,到叶子节点就加一。

代码

 1const int inf = 0x3f3f3f3f;
 2const int mxn = 1e3 + 5;
 3
 4vector<int> a[mxn];
 5int num[mxn];
 6
 7void dfs(int rt, int &d, int h){
 8    d = max(d, h);
 9    if(a[rt].size() == 0){
10        num[h]++;
11        return ;
12    }
13    for(int i=0; i<a[rt].size(); i++){
14        dfs(a[rt][i], d, h+1);
15    }
16}
17
18int main()
19{
20    int n, m;
21    scanf("%d %d", &n, &m);
22
23    for(int i=0; i<m; i++){
24        int f, k, s;
25        scanf("%d %d", &f, &k);
26        while(k--){
27            scanf("%d", &s);
28            a[f].push_back(s);
29        }
30    }
31    int d = 0;
32    dfs(1, d, 0);
33
34    for(int i=0; i<=d; i++){
35        if(i) printf(" ");
36        printf("%d", num[i]);
37    }
38    printf("\n");
39    return 0;
40}