A1094 The Largest Generation (25 point(s))

BFS统计层结点数

1. 原文

A family hierarchy is usually presented by a pedigree tree where all the nodes on the same level belong to the same generation. Your task is to find the generation with the largest population.

Input Specification:

Each input file contains one test case. Each case starts with two positive integers N (<100) which is the total number of family members in the tree (and hence assume that all the members are numbered from 01 to N), and M(<N) which is the number of family members who have children. Then M lines follow, each contains the information of a family member in the following format:

1
ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a family member, K (>0) is the number of his/her children, followed by a sequence of two-digit ID‘s of his/her children. For the sake of simplicity, let us fix the root ID to be 01. All the numbers in a line are separated by a space.

output Specification:

For each test case, print in one line the largest population number and the level of the corresponding generation. It is assumed that such a generation is unique, and the root level is defined to be 1.

Sample Input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
23 13
21 1 23
01 4 03 02 04 05
03 3 06 07 08
06 2 12 13
13 1 21
08 2 15 16
02 2 09 10
11 2 19 20
17 1 22
05 1 11
07 1 14
09 1 17
10 1 18

Sample output:

1
9 4

2. 解析

层序遍历结点level[deep]++;

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
vector<int> v[110];
int deep=1;
int level[110]={};
void bfs(int root){
queue<int> q;
q.push(root);
int lastnode=root;
int nownode=0;
while(!q.empty()){
int temp=q.front();
//printf("%d\n",temp);
level[deep]++;
q.pop();
for (int i = 0; i < v[temp].size(); ++i)
{
q.push(v[temp][i]);
nownode=v[temp][i];
}
if (lastnode==temp)
{
deep++;
lastnode=nownode;
}
}
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for (int i = 0; i < m; ++i)
{
int id,k,a;
scanf("%d%d",&id,&k);
for (int j = 0; j < k; ++j)
{
scanf("%d",&a);
v[id].push_back(a);
}
}
bfs(1);
int maxnum=-1; int maxidx=0;
for (int i = 1; i <= deep; ++i)
{
int size=level[i];
if (size>maxnum)
{
maxnum=size;
maxidx=i;
}

}
printf("%d %d\n",maxnum,maxidx);
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1094/
  • 发布时间: 2019-09-03 12:31
  • 更新时间: 2021-10-29 14:07
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!