PAT (Advanced Level) 1004. Counting Leaves (30)

来源:互联网 发布:秦风拍牌软件 编辑:程序博客网 时间:2024/05/21 22:30

1004. Counting Leaves (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 101 1 02
Sample Output
0 1

这道题我还是很苦恼的,在没有看标准代码之前,我不知道要用什么容器去承载这些数字,不知道该用什么想法去获得每一层的叶子节点个数,最原始的想法就是用数组来装,然后用结构体数组来挨个标记他们的孩子节点和父亲节点,他们的层数再通过父亲节点往回找到直到数值为1。。。

后来觉得自己还是对DFS不熟悉,其实看到题目就应该反映出来这是一道用DFS来遍历树从而递归获得所有叶子节点的层数,然后就可以将相应层数的叶子节点个数++。我们只需要关心叶子节点就好了,其他的没有到达递归边界的都不是叶子节点,我们不需要关心他们在哪一层~然后就是用vector~~还是不习惯啊

#include<cstdio>#include<algorithm>#include<vector>using namespace std;const int maxn = 110;vector<int> G[maxn];int leaf[maxn] = { 0 };int max_h = 1;int n, m, parent, child, k;void DFS(int index, int h) {max_h = max(max_h, h);if (G[index].size() == 0) {printf("h: %d\n", h);printf("leaf[h]: %d\n",leaf[h]);leaf[h]++;return;}for (int i = 0; i < G[index].size(); i++) {DFS(G[index][i],h+1);}}int main() {scanf("%d%d", &n, &m);for (int i = 0; i < m; i++) {scanf("%d%d", &parent, &k);for (int j = 0; j < k; j++) {scanf("%d", &child);G[parent].push_back(child);}}DFS(1,1);//printf("%d ", max_h);for (int h = 1; h <= max_h; h++) {printf("%d", leaf[h]);if (h < max_h ) {printf(" ");}else {printf("\n");}}return 0;}

0 0
原创粉丝点击