1004. Counting Leaves (30)
题目:
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
题目描述:
对于一个家族树,输出每层节点中 叶子节点(即没有孩子)的数量
分析
利用 vector 采用树的静态写法,构建家族树。将树中的每个成员封装成结构体,用队列实现树的中序遍历,加入当前结点孩子到队列中时,层数加一即可。
代码
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
int a[100]; //保存每层叶子节点的个数
struct node{
int id;
int layer;
node(){}
node(int i,int l):id(i),layer(l){}
};
vector <int> v[100];
queue <node> q;
int main(void){
int n,m,k;
int parentId,children;
cin>>n>>m;
for(int i = 0;i < m;i++){
cin>>parentId>>k;
for(int j = 0;j < k;j++){
cin>>children;
v[parentId].push_back(children);
}
}
memset(a,0,sizeof(a));
q.push(node(01,1)); //将第一层的父结点加入到队列中
int maxLayer = 1; //01 占第一层,所以初始化为一
while(!q.empty()){
node temp = q.front();
q.pop();
if(v[temp.id].size() == 0){
a[temp.layer]++;
}else{
//b遍历其孩子
for(int i = 0;i < v[temp.id].size();i++){
//将孩子加入队列,层数加一
q.push(node(v[temp.id][i],temp.layer+1));
//保存最大层数
maxLayer = max(maxLayer,temp.layer+1);
}
}
}
for(int i = 1;i < maxLayer;i++)
cout<<a[i]<<" ";
cout<<a[maxLayer]<<endl;
return 0;
}