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, 节点数
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.(为了简单起见,让我们将根ID固定为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 1
2 1
01 1 02
Sample Output 2
0 1
Sample Input 2
6 2
01 3 02 03 04
02 2 05 06
Sample Output 2
0 2 2
// 代码 -------------------------------------------------------------------------
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 110;
int N, M;
int leafNum[MAXN], levelNum[MAXN], maxLevelNum;
struct node {
vector<int> child;
} Node[MAXN];
void BFS(int st) {
levelNum[st] = 0;
queue<int> q;
q.push(st);
while(!q.empty()) {
int front = q.front();
q.pop();
if(Node[front].child.size() != 0) {
for(int i=0; i<Node[front].child.size(); i++) {
q.push(Node[front].child[i]);
levelNum[Node[front].child[i]] = levelNum[front] + 1;
maxLevelNum = levelNum[Node[front].child[i]];
}
} else leafNum[levelNum[front]]++;
}
}
int main() {
scanf("%d%d",&N,&M);
for(int i=0; i<M; i++) {
int ID, K;
scanf("%d%d",&ID,&K);
for(int j=0; j<K; j++) {
int currentChild;
scanf("%d",¤tChild);
Node[ID].child.push_back(currentChild);
}
}
BFS(1);
for(int i=0; i<=maxLevelNum; i++) {
printf("%d",leafNum[i]);
if(i != maxLevelNum) printf(" ");
}
return 0;
}
1004 Counting Leaves (30)
最新推荐文章于 2022-07-26 16:28:25 发布