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
结尾无空行
一开始读题,以为是家庭成员,求有多少个家庭问题,上来就直接并查集了,结果写完才发现,此题要求的是,第几代人最多人数,然后求出来,画出树形图:
图画的有点草率了,见谅,从图中可以看出,第四代人的个数最多,一共有 9 个人,就是我们要输出的结果,所以,此题我们采用深度优先搜索进行解答。
定义数组 v 记录路径信息
定义 vis 判断是否访问过
定义 map<int, vector> 键指的是层数, 值指的是每层都有什么人。
首先,根据 m 求出所有的 v 图,需要注意的是,我们不确定谁才是根节点,所以,我这里开始用 vis 判断根节点,如果某个人没在孩子里出现,那么他就是祖先。
找到祖先,深搜,每次让那层人加入到 map 中。
最后一次遍历,求出 层数和最大人数即可。
#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set>
#include<unordered_map>
#include<fstream>
#include<cstring>
using namespace std;
const int N = 101;
vector<int> v[N];
bool vis[N] = {false};
map<int, vector<int>> mp;
void Dfs(int x, int level) {
mp[level].push_back(x);// x 是该层的人,加入 map
vis[x] = 1;// 标记访问
for (int i = 0; i < v[x].size(); i++) {
if (!vis[v[x][i]]) {// 如果没访问过,深搜
Dfs(v[x][i], level + 1);
}
}
}
int main () {
int n, m;
cin >> n >> m;
while (m--) {
int id, k;
cin >> id >> k;
for (int i = 0; i < k; i++) {
int x;
cin >> x;
v[id].push_back(x);
vis[x] = true;// 孩子标记
}
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {// 找到祖先
memset(vis, 0, sizeof(vis));
Dfs(i, 1);
break;
}
}
int sum = 0, level = 0;
for (auto it = mp.begin(); it != mp.end(); it++) {
if (it->second.size() > sum) {// 找到最大层数的人
sum = it->second.size();
level = it->first;
}
}
cout << sum << " " << level;
return 0;
}
标签:1094,25,vis,Generation,generation,level,int,include,ID 来源: https://blog.csdn.net/weixin_45962741/article/details/121487057