原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805372601090048
题目描述
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.
输入描述:
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.
输出描述:
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.
输入例子:
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
输出例子:
9 4
题意就是给出节点数和关系数,然后每个关系数描述该点的孩子有哪些,最后组成一棵树。然后问你这棵树里节点最多的一层有多少个节点和具体是哪一层,使用BFS算法逐层遍历记录就好。一开始牛客过了再提交到PTA官网喜提WA,原来是漏了万一最多的节点层在最后一层的情况(这在牛客上居然也能过,牛客数据似乎真有点水=。=),这里记录一下自己的错误,顺便看一下有没有后人也踩坑遇到自己还没找到错误,然后就随手补个条件判断就好了。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int n,m,ans_num=1,ans_gen=1,prev_gen=1,prev_num=1;
vector<int> v[105];
struct node
{
int gen,id;
node(int gen=1,int id=1)
{
this->gen=gen;
this->id=id;
}
};
queue<node> q;
int main()
{
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++)
{
int id,k;
scanf("%d %d",&id,&k);
for(int j=0;j<k;j++)
{
int idk;
scanf("%d",&idk);
v[id].push_back(idk);//记录每个点的子节点
}
}
for(int i=0;i<v[1].size();i++)
q.push(node(2,v[1][i]));//第一层先压队列
while(!q.empty())
{
node now=q.front();
q.pop();
if(now.gen!=prev_gen)//每次到了全新一层就判断是否更新答案与更新层数
{
if(prev_num>ans_num)
{
ans_num=prev_num;
ans_gen=prev_gen;
}
prev_gen=now.gen;
prev_num=0;
}
prev_num++;
for(int i=0;i<v[now.id].size();i++)
q.push(node(prev_gen+1,v[now.id][i]));
}
if(prev_num>ans_num)//这里注意判断一下,因为可能节点最多的在最后一层
{
ans_num=prev_num;
ans_gen=prev_gen;
}
printf("%d %d",ans_num,ans_gen);
return 0;
}