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<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
.
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
做题思路:
已知所有ID都用两个数字表示,所以ID可以用int类型存储
已知根节点固定为01,那么可以从根节点开始遍历所有子节点,并将所有子节点放入队列。可以保证深度小的一定在队列前面。同时记录下一层所有子节点的个数,根据统计的个数确定该层范围,然后记录无子节点的节点数并输出
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define rep(i,a,n) for(int i=a;i<=n;i++)
int n,m,sign=0;
queue<int> ID[110];
queue<int> q;
bool st[110]; //标记编号是否出现过
void bfs(){
int t,num=1;
q.push(1); // let us fix the root ID to be 01
while(q.size()){
int count=0,k=0; //count记录无子叶的结点数目,k记录一层的节点数目
rep(j,1,num){
t=q.front();
q.pop(); //每次取出当前层的一个结点来检查是否有子节点
if(ID[t].empty()) count++;
else{
while(ID[t].size()){
q.push(ID[t].front());
ID[t].pop(); //将子节点一个个放入
k++;
}
}
}
num=k;
if(sign) cout<<' '<<count;
else {cout<<count; sign=1;}
}
return ;
}
int main()
{
cin>>n>>m;
rep(i,1,m){ //Then M lines follow
int id,k;
cin>>id>>k;
if(!st[id]){ st[id]=1;}
while(k--){
int sID;
cin>>sID;
if(!st[sID]){ st[sID]=1;}
ID[id].push(sID);
}
}
bfs();
return 0;
}
//思路:分层分结点讨论,分层计数无子节点的节点
//用邻接矩阵计算不太合适,复杂度太大会超时
注意ID的输入可能是无序的