原题
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.
题目翻译
家族等级通常由一棵血统树来呈现。您的任务是统计那些没有子女的家庭成员。
输入规范:
每个输入文件包含一个测试用例。每个案例以一行开始,其中包含 0<N<100(树中节点总数)和 M (<N)(非叶子点数)。然后是 M 行,每行格式如下
ID K ID[1] ID[2] ... ID[K]
其中,ID 是一个两位数,代表一个给定的非叶子节点,K 是其子节点的数量,之后是其子节点的一系列两位数 ID。为简单起见,我们将根节点的 ID 定为 01。输入结束时,N 为 0。
输出规范:
对于每个测试用例,应从根节点开始,按年资级别统计没有子女的家庭成员。这些数字必须打印在一行中,中间用空格隔开,每行末尾不得有多余的空格。
示例表示一棵只有 2 个节点的树,其中 01 是根节点,02 是其唯一的子节点。因此,在根节点 01 上有 0 个叶节点,而在下一级上有 1 个叶节点。那么我们应该在一行中输出 0 1。
解题思路
本题考查树的遍历,选择用bfs对树的每一层进行遍历。queue中储存叶子节点的子节点,而非叶子节点则记入答案。
代码
#include <bits/stdc++.h>
#include <queue>
using namespace std;
const int N = 110;
int n, m;
int h[N], e[N], ne[N], idx;
int ans[N], depth; // ans为答案数组,depth为遍历深度
void add(int a, int b){ // 链表储存
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int main(){
cin >> n >> m;
memset(h, -1, sizeof h);
for(int i = 0; i < m; i++) {
int id, k;
cin >> id >> k;
while(k--){
int x;
cin >> x;
add(id, x);
}
}
queue<int> q;
q.push(1); // 将01存入队列
while(q.size()){
int s = q.size(); // s为当前需要遍历的点的个数
for(int i = 0; i < s; i++){
int u = q.front();
q.pop();
if(h[u] == -1) ans[depth]++; // 如果为叶子节点,存入答案
else
for(int j = h[u]; j != -1; j = ne[j])
q.push(e[j]); // 否则将子节点存入队列
}
depth++;
}
cout << ans[0]; // 注意输出格式
for(int i = 1; i < depth; i++) cout << " " << ans[i];
return 0;
}