1004. Counting Leaves (30)

Posted yuxiaoba

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1004. Counting Leaves (30)相关的知识,希望对你有一定的参考价值。

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

 

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
 1 #include<stdio.h>
 2 #include<math.h>
 3 #include<stdlib.h>
 4 
 5 struct Node
 6 {
 7     int father;  //父节点
 8     int level;   //层数
 9     int isNochild;  //是否没有孩子,没有孩子置1
10 }node[101];
11 int ans[101];  
12 int main()
13 {
14     int n,m,mlevel=1;
15     int i,j,k,id,child;
16     scanf("%d%d",&n,&m);
17     for( i=0; i<=100; i++)
18     {
19         node[i].father = 0;
20         node[i].level=0;
21         node[i].isNochild=1;
22     }
23     for( i=0; i<m; i++ )
24     {
25         scanf("%d%d",&id,&k);
26         node[id].isNochild=0;  //id结点有孩子
27         for( j=0; j<k; j++)
28         {
29             scanf("%d",&child);
30             node[child].father=id; //child结点的父结点是id
31         }
32     }
33     node[1].level=1;  //根节点的层数为1
34     for( i=1; i<=n; i++)
35     {
36         for( j=1; j<=n; j++)
37         {
38             if( node[j].father==i)
39             {
40                 node[j].level=node[i].level+1; //如果有父节点,结点层数等于父节点层数加1
41                 if( node[j].level>mlevel)
42                     mlevel = node[j].level;
43             }
44         }
45     }
46     for( i=1; i<=n; i++)
47         if( node[i].isNochild==1)
48              ans[node[i].level]++;  //如果没有孩子,目标数组+1
49 
50     printf("%d",ans[1]);
51     for( i=2; i<=mlevel; i++)
52         printf(" %d",ans[i]);
53     return 0;
54 }

 

以上是关于1004. Counting Leaves (30)的主要内容,如果未能解决你的问题,请参考以下文章

1004 Counting Leaves (30 分)

1004. Counting Leaves (30)

1004. Counting Leaves (30)

1004. Counting Leaves (30)

1004 Counting Leaves (30)

PAT 1004 Counting Leaves (30分)