PAT甲级 1004

来源:互联网 发布:重庆大学生就业知乎 编辑:程序博客网 时间:2024/05/16 17:21

Counting Leaves

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


用2个vector分别记录每个节点的孩子结点ID和每一层的结点ID。然后使用isLeaf数组判断某一节点是否有孩子。

#include<iostream>#include<stdio.h>#include<limits.h>#include<algorithm>#include<vector>using namespace std;const int maxn=100+1;vector<int> v[maxn],level[maxn];bool isLeaf[maxn];int maxHeight=0;void dfs(int cur,int height){    for(auto it=v[cur].begin();it!=v[cur].end();it++){        level[height].push_back(*it);        dfs(*it,height+1);    }    maxHeight=max(maxHeight,height);}int main(){    freopen("./in","r",stdin);    int n,m;    scanf("%d %d",&n,&m);    fill(isLeaf,isLeaf+n+1,true);    int i,j;    int id,k,tid;    for(i=0;i<m;i++){        scanf("%d %d",&id,&k);        if(k!=0){            isLeaf[id]=false;        }        for(j=0;j<k;j++){            scanf("%d",&tid);            v[id].push_back(tid);        }    }    level[1].push_back(0);    dfs(1,2);    if(isLeaf[1]){        printf("1");    }else{        printf("0");    }    int cnt;    for(i=2;i<maxHeight;i++){        cnt=0;        for(auto it=level[i].begin();it!=level[i].end();it++){            if(isLeaf[*it]){                cnt++;            }        }        printf(" %d",cnt);    }}
原创粉丝点击