1094 The Largest Generation (25 分)
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:
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
此题存入的是结构体,在BFS的过程中同步完成对gen(结点所处的gen)的初始化
用一个数组来记录gen里结点的个数
最后输出gen里结点最大个数与此时的gen
#include<cstdio>
#include<iostream>
#include<vector>
#define MAX 110
using namespace std;
typedef struct PER{
int id;
int gen;
}PER;
int num[MAX]={0};
vector<PER>adl[MAX];
void bfs(PER &root)
{
int inque[MAX]={0};//入过队列
PER que[MAX];
int front=-1;int rear=-1;
que[++rear]=root;
inque[root.id]=1;
root.gen=1;
num[root.gen]++;
while(front!=rear)
{
//出队
PER out=que[++front];
//邻接表项入队
for(int i=0;i<adl[out.id].size();i++)
{
if(inque[adl[out.id][i].id]==0)
{
adl[out.id][i].gen=out.gen +1;
que[++rear]=adl[out.id][i];
inque[adl[out.id][i].id]=1;
num[adl[out.id][i].gen]++;
}
}
}
}
int main()
{
int n,m;cin>>n>>m;
for(int i=0;i<m;i++)
{
int id;cin>>id;
int cn;cin>>cn;//childNum
for(int i=0;i<cn;i++)
{
PER child;cin>>child.id;
adl[id].push_back(child);
}
}
PER root;
root.gen=1;
root.id=1;
bfs(root);
// //check gen's num
// for(int i=0;i<MAX;i++)
// {
// if(num[i]!=0)
// cout<<i<<":"<<num[i]<<"amount"<<endl;
// }
// //check adl
// for(int i=0;i<MAX;i++)
// {
// if(adl[i].size()==0)continue;
// else
// {
// printf("%02d: ",i);
// for(int j=0;j<adl[i].size();j++)
// {
// cout<<adl[i][j].id<<"-"<<adl[i][j].gen<<" ";
// }
// cout<<endl;
// }
// }
int maxNum=0,maxGen=0;
for(int i=0;i<MAX;i++)
{
if(num[i]!=0&&num[i]>maxNum)
{
maxNum=num[i];
maxGen=i;
}
}
cout<<maxNum<<" "<<maxGen;
}