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.
每一个测试样例一开始是两个正整数 N(<100):分别代表家族成员总数 (家庭成员编号从01-N) M(<N):家族成员中有孩子的人的数量
其后有M行,每一行包含了一个家庭成员的信息,格式如下:
ID K ID【1】ID【2】。。。ID【k】
ID是一个两位数代表了一个家庭成员,K是他孩子的数量,其后跟着K个他孩子们的ID。为简单起见,将根节点ID固定为01
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.
输出最多的人数以及相应的那一代的层次。假设那一代是独一无二的,根节点层次设为1
思路:建树-遍历树。通过遍历树记录每一层结点数。最后通过比较得到最大值以及所在层
#include<cstdio>
#include<vector>
using namespace std;
const int maxn = 110;
vector<int> NODE[maxn];//树的静态写法
int hashTable[maxn]={0};//记录每一层结点数
void DFS(int index,int level){
hashTable[level]++;
for(int j=0;j<NODE[index].size();j++){
DFS(NODE[index][j],level+1);
}
}
int main(){
int n,m,parent,k,child;
scanf("%d%d",&n,&m);
//------建树----------
for(int i=0;i<m;i++){
scanf("%d%d",&parent,&k);
for(int j=0;j<k;j++){
scanf("%d",&child);
NODE[parent].push_back(child);
}
}
DFS(1,1);
//-----寻找最大值-----
int maxLevel=-1,maxValue=0;
for(int i=1;i<maxn;i++){
if(hashTable[i]>maxValue){
maxValue=hashTable[i];
maxLevel = i;
}
}
//------输出---------
printf("%d %d\n",maxValue,maxLevel);
return 0;
}