码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1004 Counting Leaves

时间:2019-05-20 21:27:17      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:return   stdio.h   book   lan   开始   vector   roo   NPU   cto   

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

标签:return   stdio.h   book   lan   开始   vector   roo   NPU   cto   

原文地址:https://www.cnblogs.com/kazama/p/10896313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!