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
题目意思就是给出结点总数、叶子结点总数、每个非叶子结点的孩子结点。输出每层的叶子结点数目。很明显的层序遍历。
第一:结点的表示:
struct node {
int id;
vector<int> next;//保存本节点的孩子结点,没有孩子next.size()==0
};
第二:如何判断一层的结束,简单点就是插入一个特殊的结点,本题因为结点编号从1开始,所以使用一个编号为-1的结点来隔开层与层。
第三:使用队列
#include <iostream>
#include <cstdio>
#include <string.h>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <climits>
using namespace std;
const int inf=INT_MAX;
struct node {
int id;
vector<int> next;
};
int main() {
int N,M;
cin>>N>>M;
vector<node> vec;
vec.push_back({-1});
for(int i=1; i<=N; i++) {
node a;
a.id=i;
vec.push_back(a);
}
for(int i=0; i<M; i++) {
int id,num;
cin>>id>>num;
for(int m=0; m<num; m++) {
int b;
cin>>b;
vec[id].next.push_back(b);
}
}//数据读取完毕了
vector<int> out;//用于输出结果
queue<node> que;
que.push(vec[1]);
que.push({-2});//插入层间隔
//当只剩下一个层间隔结点时候就是遍历完成的时候
while(!(que.size()==1&&que.front().id==-2)) {
int num=0;
while(que.front().id!=-2) {
node get=que.front();
que.pop();
if(get.next.size()==0) {
num++;
continue;
}
for(int i=0; i<get.next.size(); i++) {
que.push(vec[get.next[i]]);
}
}
//这个get 的id一定是-2了,标示一层的完结
//我们需要把位于队首的层间隔结点移动到队尾
node get=que.front();
que.pop();
out.push_back(num);
que.push(get);
}
for(int i=0;i<out.size();i++){
if(i==0)
cout<<out[i];
else
cout<<' '<<out[i];
}
}