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 思路:很简便的遍历。 注意记录每层最后一个节点的情况。
1 #include <iostream> 2 #include <vector> 3 #include <cstdio> 4 #include <queue> 5 using namespace std; 6 #define MAX 110 7 struct Node 8 { 9 vector<int>child; 10 }node[MAX]; 11 int out[MAX]; 12 int ipt=0; 13 void BFS(int root) 14 { 15 queue<int>Q; 16 int pt=root; //指向一层的最后一个节点 17 int num=0; //记录每行的无孩子节点 18 Q.push(root); 19 int nextlevelpt; 20 while(!Q.empty()) 21 { 22 int now=Q.front(); 23 Q.pop(); 24 if(node[now].child.size()==0) 25 num++; 26 if(now==pt) 27 { 28 out[ipt++]=num; 29 num=0; 30 } 31 for(int i=0;i<node[now].child.size();i++) 32 { 33 if(i==node[now].child.size()-1) //此处应该注意是一行的最后一个节点采取此种方法。 34 nextlevelpt=node[now].child[i]; 35 Q.push(node[now].child[i]); 36 } 37 if(now==pt) 38 pt=nextlevelpt; 39 } 40 } 41 int main(int argc, char *argv[]) 42 { 43 int N,M; 44 scanf("%d%d",&N,&M); 45 for(int i=0;i<M;i++) 46 { 47 int father; 48 scanf("%d",&father); 49 int K; 50 scanf("%d",&K); 51 for(int i=0;i<K;i++) 52 { 53 int child; 54 scanf("%d",&child); 55 node[father].child.push_back(child); 56 } 57 } 58 BFS(1); 59 for(int i=0;i<ipt;i++) 60 { 61 printf("%d",out[i]); 62 if(i!=ipt-1) 63 printf(" "); 64 } 65 putchar(‘\n‘); 66 return 0; 67 }