1004. Counting Leaves (30)

来源:互联网 发布:wubi安装ubuntu的缺点 编辑:程序博客网 时间:2024/05/29 02:48
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

#include <iostream>#include <cstdio>#include <cstring>#define N 105struct node {int child[N];int k;}s[N];int que[N*N];void init() {int i;for (i = 0; i < N; i++)s[i].k = 0;}int main() {int n,m,i,j,l,r,count,k,t;while (scanf("%d%d",&n,&m) != EOF) {init();for (t = 0; t < m; t++) {scanf("%d",&i);scanf("%d",&s[i].k);for (j = 0; j < s[i].k; j++) {scanf("%d",&s[i].child[j]);}}que[0] = 1;//根节点的编号是1k = 1;//k表示当前的节点的子节点(孩子节点)//lfor (l = 0, r = 1,t = 0; l < k; r = k,t++) {count = 0;for (; l < r; l++) {i = que[l];if (!s[i].k) count++;for (j = 0; j < s[i].k; j++) {que[k++] = s[i].child[j];}}if (t) printf(" %d",count);else printf("%d",count);}printf("\n");}return 0;}

0 0
原创粉丝点击