1004. Counting Leaves

Q: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

A: 求每一层叶节点的个数。

这里有两个考察点:1.如何从已知条件,简单的用数据结构表示树。tree[i][j] = 1;表示i是父节点,j是子节点。

2.这里只要求叶节点的个数,不需要求出每个叶节点的编号,dfs,bfs都可以。dfs简单一点。

#include<stdio.h>
#include<string.h>

int tree[100][100];
int n,m;
int count[100];
int maxLevel;

void dfs(int id,int level)
{
    int haveChild = 0;
    int i;
    if(level>maxLevel)
        maxLevel = level;

    for(i=1;i<=n;i++)
    {
        if(tree[id][i]==1)   //has a edge
        {
            haveChild = 1;   //id is not a leaf
            dfs(i,level+1);
        }
    }

    if(haveChild==0)   //id is a leaf,计数加一
        count[level]++;
}

int main()
{
    int i,j;
    int parent,childnum,child;

    memset(tree,sizeof(tree),0);
    for(i=0;i<100;i++)
        count[i] = 0;
    maxLevel = -1;

    scanf("%d %d",&n,&m);
    for(i=0;i<m;i++)
    {
        scanf("%d %d",&parent,&childnum);
        for(j=0;j<childnum;j++)
        {
            scanf("%d",&child);
            tree[parent][child] = 1;  //表示出树的结构
        }
    }
    dfs(1,0);
    for(i=0;i<maxLevel;i++)
        printf("%d ",count[i]);
    printf("%d\n",count[maxLevel]);
    return 0;
}

  

posted @ 2013-07-13 21:39  summer_zhou  阅读(374)  评论(0编辑  收藏  举报