1004. Counting Leaves (30)
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 Input2 1 01 1 02Sample Output
0 1
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int id ;
int num ;
int a[100] ;
} node ;
static nums[10000];
static node nodes[10000] ;
static int n = 0 ;
static int m = 0 ;
static int mx = 0 ;
void getNode(int id , node nd[]){
int i = 0 ;
int nm = 0 ;
for( i = 0 ; i < m ; i ++ ){
if( nodes[i].id==id ){
nd[0] = nodes[i];
nm++;
break;
}
}
if(nm==0){
nd[0].num=-1;
}
}
void dfs(int id , int level){
if(mx < level){
mx = level;
}
int i ;
node nd[1] ;
getNode(id,nd);
if(nd[0].num==-1){
nums[level]++;
return ;
}
for( i = 0 ; i <nd[0].num ; i++ ){
dfs(nd[0].a[i] , level+1 );
}
}
int main(){
int i ,j;
scanf("%d",&n);
scanf("%d",&m);
for( i = 0 ; i < m ; i++ ){
scanf("%d",&nodes[i].id );
scanf("%d",&nodes[i].num );
for(j=0;j<nodes[i].num ; j++){
scanf("%d",&nodes[i].a[j]);
}
}
dfs(1,0);
for(i = 0 ; i <= mx ; i++ ){
if(i==0) printf("%d" ,nums[i] );
else printf(" %d" ,nums[i] );
}
return 0;
}
本文介绍了一个计数家族树中叶子节点数量的问题,并提供了一段C语言代码实现。输入包括节点总数、非叶子节点数量及各非叶子节点的子节点信息,输出则是从根节点开始各层级的叶子节点数量。
373

被折叠的 条评论
为什么被折叠?



