1004 Counting Leaves (30)

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

题目大意:给出一棵树,找到同意深度的叶子节点的个数。 树是以数组的形式给出的;
思路: 用vector变量来构建树,v[i]中保存的是结点i的孩子。 用dfs()遍历树, 需要维护两个变量,root, depth,分别表示当前节点以及节点深度。 遍历到叶子节点的标志是v[i].size()=0;此时把当前深度的叶子节点个数更新。此外还需要记录数的最深深度,便于之后的输出;
 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 vector<int> v[101], ans(101, 0);
 5 int maxdepth=-1;
 6 
 7 void dfs(int root, int depth){
 8   if(v[root].size()==0){
 9     ans[depth]++;
10     if(depth>maxdepth) maxdepth=depth;
11     return;
12   }
13   for(int i=0; i<v[root].size(); i++) dfs(v[root][i], depth+1);
14 }
15 int main(){
16   int n, m, i, id, k,j, child, root;
17   cin>>n>>m;
18   for(i=0; i<m; i++){
19     cin>>id>>k;
20     for(j=0; j<k; j++){
21       cin>>child;
22       v[id].push_back(child);
23     }
24   }
25   dfs(1, 0);
26   for(i=0; i<=maxdepth; i++) {
27     if(i==0) cout<<ans[i];
28     else cout<<" "<<ans[i];
29   }
30   return 0;
31 }


猜你喜欢

转载自www.cnblogs.com/mr-stn/p/9152575.html