A1004. Counting Leaves

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
 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
typedef struct NODE{
vector<int>child;
int layer;
}node;
node tree[];
int N, M, cnt[] = {,}, depth = -;
void levelOrder(int root){
queue<int> Q;
tree[root].layer = ;
Q.push(root);
while(Q.empty() == false){
int temp = Q.front();
if(tree[temp].layer > depth)
depth = tree[temp].layer;
Q.pop();
if(tree[temp].child.size() == ){
cnt[tree[temp].layer]++;
}
int len = tree[temp].child.size();
for(int i = ; i < len; i++){
tree[tree[temp].child[i]].layer = tree[temp].layer + ;
Q.push(tree[temp].child[i]);
}
}
}
int main(){
int tempc, tempd, tempe;
scanf("%d%d", &N, &M);
for(int i = ; i < M; i++){
scanf("%d%d", &tempc, &tempd);
for(int j = ; j < tempd; j++){
scanf("%d",&tempe);
tree[tempc].child.push_back(tempe);
}
}
levelOrder();
for(int i = ; i <= depth; i++){
if(i != depth)
printf("%d ", cnt[i]);
else printf("%d", cnt[i]);
}
cin >> N;
return ;
}

总结:

1、题意:题目要求计算从根开始每一层的没有孩子的家庭成员。其实从题目上就知道,就是计算每一层的叶节点个数。

2、使用一个hash数组,以层数为下标索引。使用层序遍历来计算出每一个节点的层数。每次访问节点时,如果该节点没有子树,则将其所在layer的hash数组加一。

上一篇:Spring Boot中@Scheduled注解的使用方法


下一篇:js md5 中文