PAT 1094 The Largest Generation——简单BFS应用

题目

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 (

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:
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:
9 4
结尾无空行

解析

题意

一个家族树,要求找出该家族树中,人数最多的一代人,并输出最多一代人的人数及是第几代。

解题思路:

简单BFS,只需要在遍历的时候记录当前层共有多少个人,然后每一层遍历结束比较该层人数和前几层人数中的最大值,并记录最大值及对应层数,最后输出即可。

代码详解

#include"bits/stdc++.h"
#include
#include
#define MAXNUM 102
using namespace std;

struct Node
{
	vector<int> children;
}Tree[MAXNUM];

int main()
{
	ios::sync_with_stdio(false);
	int N,M;
	int count[MAXNUM];
	fill(count,count+MAXNUM,0);
	cin>>N>>M;
	while(M--)
	{
		int id,n;
		cin>>id>>n;
		while(n--)
		{
			int child;
			cin>>child;
			Tree[id].children.push_back(child);
		}
	}
	// BFS
	int maxn=0,loc=0,level=1;
	queue<int> q;
	q.push(1);
	while(!q.empty())
	{
		int l = q.size();
		level++;
		for(int i=0;i<l;i++)
		{	
			int now=q.front();
			for(vector<int>::iterator it=Tree[now].children.begin();it != Tree[now].children.end() && !Tree[now].children.empty();it++)
			{
				q.push(*it);
				count[level]++;
				if(count[level] > maxn)
				{
					maxn= count[level];
					loc = level;
				}
			}
			q.pop();
		}
	}
	if(maxn == 0)
        cout<<1<<" "<<1;
	else cout<<maxn<<" "<<loc;
	return 0;
}

你可能感兴趣的:(算法练习,算法,数据结构)