题目:
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-digit ID
's of its children. For the sake of simplicity, let us fix the root ID to be 01
.
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 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
题目分析:
BFS宽搜,用到vector、queue。具体分析见注释。代码参考了该博客:点击跳转
代码:
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 #include<algorithm> 5 #include<cstring> 6 using namespace std; 7 int N,M; 8 int level[101]; //每个点的层数 9 int ans[101]; //最终的结果:每一层的叶子结点 10 vector<int> child[101]; //每个点含有的子节点 11 queue<int> aqueue; //队列 12 13 int main(){ 14 memset(ans,0,sizeof(ans)); 15 cin>>N>>M; 16 int id; 17 int num; 18 int childpoint; 19 for(int i=0;i<M;i++){ 20 cin>>id>>num; 21 for(int j=0;j<num;j++){ 22 cin>>childpoint; 23 child[id].push_back(childpoint); 24 } 25 } 26 aqueue.push(1); //第一个结点进入队列 27 level[1]=1; //第一层的结点是1 28 int nowLevel=1; //当前的层数 29 while(!aqueue.empty()){ 30 int thisId=aqueue.front(); //取出队列最前的结点 31 aqueue.pop(); 32 vector<int>::iterator it; 33 for(it=child[thisId].begin();it!=child[thisId].end();it++){ //遍历该结点的所有子结点 34 level[*it]=level[thisId]+1; //每一个子节点的层数是父节点+1 35 nowLevel=max(nowLevel,level[*it]); //对当前的层数进行更新 36 if(child[*it].size()==0){ //若该子结点没有子节点即为叶子结点,对应层的叶子结点+1 37 ans[level[*it]]++; 38 } 39 aqueue.push(*it); 40 } 41 } 42 if(N==1&&M==0){ //当只有一个根结点的情况 43 cout<<"1"; 44 }else{ 45 for(int i=1;i<=nowLevel;i++){ 46 if(i==1){ 47 cout<<ans[i]; 48 }else{ 49 cout<<" "<<ans[i]; 50 } 51 } 52 } 53 return 0; 54 }