1004 Counting Leaves
Statement
Metadata
- 作者: CHEN, Yue
- 单位: 浙江大学
- 代码长度限制: 16 KB
- 时间限制: 400 ms
- 内存限制: 64 MB
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
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
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
Sample Output
Solution
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n, m, Max, ans[N];
vector<vector<int>> G;
void dfs(int u, int dep) {
Max = max(Max, dep);
if (G[u].size() == 0) {
++ans[dep];
}
for (auto &v : G[u]) {
dfs(v, dep + 1);
}
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
memset(ans, 0, sizeof ans);
G.clear();
G.resize(n + 10);
Max = 0;
for (int i = 1, sze, u; i <= m; ++i) {
scanf("%d%d", &u, &sze);
for (int j = 1, v; j <= sze; ++j) {
scanf("%d", &v);
G[u].push_back(v);
}
}
dfs(1, 0);
for (int i = 0; i <= Max; ++i) {
printf("%d%c", ans[i], " \n"[i == Max]);
}
}
return 0;
}