1004. Counting Leaves (30)

来源:互联网 发布:mysql for mac 下载 编辑:程序博客网 时间:2024/04/28 14:24

1004. Counting Leaves (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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.

题意为:求每层的叶子节点数目。

网查方法,用结构体数组note[ ]存储每个节点,孩子用链表连接在节点后面。

#include<iostream>using namespace std;struct ChildLink{int ID;ChildLink *next;ChildLink(){next=NULL;}};struct Node{int K;ChildLink *Child;Node(){K=0;Child=NULL;}};Node *node;int t,count[100];void CountLeaves(int num,ChildLink *C)//网查的递归嵌套方法,求每层叶子节点数目{num++;while(C){if(node[C->ID].K==0) count[num]++;else{CountLeaves(num,node[C->ID].Child);}C=C->next;}if(t<num) t=num;}int main(){int i,j,N,M,id;ChildLink *c;cin>>N>>M;node=new Node[N+1];for(i=0;i<M;i++){cin>>id;cin>>node[id].K;for(j=0;j<node[id].K;j++){c=new ChildLink;cin>>c->ID;if(node[id].Child) c->next=node[id].Child;//链表存储node[id].Child=c;}}if(node[1].K==0){count[0]=1;}else{CountLeaves(0,node[1].Child);}for(i=0;i<t;i++){cout<<count[i]<<" ";}cout<<count[t]<<endl;return 0;}


0 0