题意大致为一个多叉树家谱,给出N个成员 1 - N,M个子树,子树分别为父节点号,子节点数,子节点编号组成,要求给出最多成员的那一层的成员数以及层数。
题目不算复杂,开始时都设为第一层,当每读一行时就把子节点的level变为父节点level+1,并将该子节点的所有子节点以及子孙结点递归增加为改变后子节点的层数累加1,原来各层也要-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:
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-digitID
's of his/her children. For the sake of simplicity, let us fix the rootID
to be01
. 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
#include<bits/stdc++.h>
using namespace std;
int L[101] = {0};
struct P{
//int father;
vector<int> vi;
int level;
P(){
level = 1;
// father = -1;
}
}p[1001];
void add(int num)
{
if(p[num].vi.size() == 0)
return;
for(int i = 0; i < p[num].vi.size(); i++)
{
int j = p[num].vi[i];
int LEV = p[num].level;
L[p[j].level]--;
L[LEV + 1]++;
p[j].level = LEV + 1;
add(j);
}
}
int main()
{
int N, M;
scanf("%d%d", &N, &M);
L[1] = N;//开始时假设都在第1层
char str[100];
for(int i = 1; i <= M; i++)
{
int num = 0;
scanf("%s", str);//遇到空格即停止
if(str[0] == '0')
num = str[1] - '0';
else
{
num = 10 * (str[0] - '0') + str[1] - '0';
}
int cnt;
scanf("%d", &cnt);
for(int j = 0; j < cnt; j++)
{
int num2 = 0;
scanf("%s", str);
if(str[0] == '0')
num2= str[1] - '0';
else
{
num2 = 10 * (str[0] - '0') + str[1] - '0';
}
p[num].vi.push_back(num2);
//p[num2].father = num;
L[p[num2].level]--;
p[num2].level = p[num].level + 1;
L[p[num2].level]++;
add(num2);
}
}
int tmax = 0, flag;
for(int i = 1;; i++)
{
if(L[i] != 0)
{
if(L[i] > tmax)
{
tmax = L[i];
flag = i;
}
}
else
break;
}
printf("%d %d\n", tmax, flag);
return 0;
}