题目描述:
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0, the number of nodes in a tree, and M (<), 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-digitID
‘s of its children. For the sake of simplicity, let us fix the root ID to be01
.The input ends with N being 0. That case must NOT be processed.
Output Specification:
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 and02
is its only child. Hence on the root01
level, there is0
leaf node; and on the next level, there is1
leaf node. Then we should output0 1
in a line.Sample Input:
2 1 01 1 02
Sample Output:
0 1
这题没什么难的,可能存父节点不存子节点难想一点,但事实上存子节点也不难,总之随便水水就好。
代码:
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 struct NODE{ 6 int father,depth; 7 bool nochild; 8 }; 9 10 int main(){ 11 int n,m,father_id,son_id,son_number,res[100]={},depth_max; 12 NODE tree[100]; 13 for (int i=0;i<=99;i++){ 14 tree[i].father=tree[i].depth=0; 15 tree[i].nochild=true; 16 } 17 cin >> n >> m; 18 for (int i=0;i<m;i++){ 19 cin >> father_id >> son_number; 20 if (son_number!=0) tree[father_id].nochild=false; 21 for (int j=0;j<son_number;j++){ 22 cin >> son_id; 23 tree[son_id].father=father_id; 24 } 25 } 26 for (int i=1;i<=n;i++){ 27 int now=i,level=1; 28 for (;tree[now].father!=0;){ 29 now=tree[now].father; 30 level++; 31 } 32 tree[i].depth=level; 33 depth_max=(depth_max>level)?depth_max:level; 34 } 35 for (int i=1;i<=n;i++){ 36 if (tree[i].nochild) res[tree[i].depth]++; 37 } 38 for (int i=1;i<depth_max;i++) 39 cout << res[i] << " "; 40 cout << res[depth_max]; 41 return 0; 42 }
原文:https://www.cnblogs.com/jarvis-yang/p/12293254.html