PAT1004 Counting Leaves

Posted kazama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT1004 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 Specification:

Each input file contains one test case. Each case starts with a line containing 0, the number of nodes in a tree, and M (<), 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.

Sample Input:

2 1
01 1 02

Sample Output:

0 1



读题和题意理解都没有问题,打印每层的叶子节点个数。
参考代码:
https://www.liuchuo.net/archives/2229

柳婼姐受我一拜!

 1 #include<iostream>
 2 #include<iomanip>
 3 #include<stdlib.h>
 4 #include<stdio.h>
 5 #include<algorithm>
 6 #include<math.h>
 7 #include<vector>
 8 using namespace std;
 9 vector<int>v[100];
10 int book[100];
11 int maxdepth=-1;
12 void dfs(int index, int depth) {
13     //结束条件
14     if (v[index].size() == 0) {
15         //那层的叶子数+1
16         book[depth]++;
17         //要统计最大层数,所以需要maxdepth
18         maxdepth = max(maxdepth, depth);
19         //不往下找了,回溯
20         return;
21     }
22     for (int i = 0; i < v[index].size(); i++) {
23         dfs(v[index][i], depth + 1);//往下找
24     }
25 }
26 int main() {
27     int n, m, id, k, c;
28     cin >> n >> m;
29     for (int i = 0; i < m; i++) {
30         cin >> id >> k;
31         for (int j = 0; j < k; j++) {
32             cin >> c;
33             v[id].push_back(c);//push_back操作一开始写错了
34         }
35     }
36     dfs(1, 0);
37     cout << book[0];
38     for (int i = 1; i <= maxdepth; i++)
39         cout << " " << book[i];
40     system("pause");
41     return 0;
42 }

 







以上是关于PAT1004 Counting Leaves的主要内容,如果未能解决你的问题,请参考以下文章

pat 1004 Counting Leaves

PAT 甲级 1004 Counting Leaves

PAT Advanced 1004 Counting Leaves

PAT 1004 Counting Leaves(结构体)

PAT 1004 Counting Leaves (30分)

PAT1004 Counting Leaves (30) 数组链式建树