题目描述
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
具体思路:
这道题可以看做无权图的单源最短路问题,求出各点到根节点的最短路径即为层数,统计路径相同的元素的个数,并从中找出最大值即可求解本题
#include<iostream>
#include<vector>
#include<map>
#include<queue>
#include<limits.h>
using namespace std;
vector<vector<int>> fmap;
vector<int> dis;
int start = 1;
map<int, int> level_cnt;
int N, M;
void Unweighted()
{
//1.元素入队
//2.判断队列是否为空
// 3.非空时元素出队
// 4.访问该元素的所有邻接点没有访问过则更新距离(和路径)并将邻接点入队
dis[0] = INT_MIN;
dis[start] = 1;//初始化起点
queue<int> q;
q.push(start); //将起点插入队列
while (!q.empty()){
int f = q.front(); q.pop();
for (int j = 0; j < N+1; j++){//遍历所有邻接点
if (dis[j] == -1 && fmap[f][j] != 0){
dis[j] = dis[f] + 1;
q.push(j);
}
}
}
}
int main(){
//1、建图
cin >> N >> M;
dis.resize(N+1, -1);
fmap.resize(N + 1, vector<int>(N + 1, 0));
for (int i = 0; i < M; i++){
int par, num ,chi;
cin >> par >> num;
for (int j = 0; j < num; j++){
cin>>chi;
fmap[par][chi] = 1;
fmap[chi][par] = 1;
}
}
//2、求单源无权图的最短路径
Unweighted();
//3、统计路径相同的情况并找出出现最多次数的路径
int maxCnt = 0, maxLevel = 0;
for (int i = 0; i < dis.size(); i++){
++level_cnt[dis[i]];
}
for (auto m : level_cnt){
if (m.second>maxCnt){
maxCnt = m.second;
maxLevel = m.first;
}
}
cout << maxCnt << " " << maxLevel;
system("pause");
return 0;
}