当前位置:网站首页>L2-026 小字辈 (25 分)
L2-026 小字辈 (25 分)
2022-08-08 16:49:00 【Here_SDUT】
本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。
输入格式: 输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。
输出格式: 首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。
输入样例:
9
2 6 5 5 -1 5 6 4 7输出样例:
4
1 9分析: 跑两次dfs,第一次找到最深的深度,第二次dfs处于最深深度的所有点就是答案。
代码:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e5+10;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
typedef pair<int,int> PII;
vector<int> ans;
int mmax = -1;
vector<int> child[maxn];
void dfs(int now, int ceng){
mmax = max(mmax, ceng);
if(child[now].size() == 0) {
return;
}
for(int i = 0; i < child[now].size(); i++) dfs(child[now][i],ceng+1);
}
void dfs2(int now, int ceng){
if(child[now].size() == 0) {
if (ceng == mmax) ans.push_back(now);
return;
}
for(int i = 0; i < child[now].size(); i++) dfs2(child[now][i],ceng+1);
}
int main(int argc, char const *argv[]) {
int n;
cin >> n;
int root;
for(int i = 1; i <= n; i++) {
int x;
cin >> x;
if(x != -1)
child[x].push_back(i);
else root = i;
}
dfs(root, 1);
dfs2(root,1);
sort(ans.begin(),ans.end());
cout << mmax << endl;
for(int i = 0; i < ans.size(); i++) {
printf("%d%c",ans[i], i == ans.size() - 1 ? '\n' : ' ');
}
return 0;
}边栏推荐
- [机缘参悟-64]:《兵者,诡道也》-5-孙子兵法解读-混战计
- 看到这个应用上下线方式,不禁感叹:优雅,太优雅了!
- Es的索引操作(代码中的基本操作)
- 差分约束做法
- D2. Sage‘s Birthday (hard version)
- Acwing Week 63 [Unfinished]
- [深入研究4G/5G/6G专题-54]: L3信令控制-3-软件功能与流程的切分-CU-UP网元的信令
- Mysql都有那些最需要掌握的原理?
- 【 8.7 】 source code - card to LCM with GCD 】 【 】
- The realization of the salary slip issuing function of WeChat public account + web background
猜你喜欢
随机推荐
jupyter notebook 隐藏&显示全部输出内容
bzoj1507 [NOI2003]Editor
leetcode:296.最佳的碰头地点
Spark cluster environment construction
ESP8266-Arduino编程实例-ADXL345三轴加速计驱动
Acwing Week 63 [Unfinished]
vi编辑器命令
spark集群环境搭建
MySQL 数据库
VIT:Transformer进军CV的里程碑
WPF StepBar
APICloud AVM 封装日期和时间选择组件
[深入研究4G/5G/6G专题-54]: L3信令控制-3-软件功能与流程的切分-CU-UP网元的信令
The situation of the solution of the equation system and the correlation transformation of the vector group
用完华为云会议解决方案,我直接卸载了之前的会议软件【华为云至简致远】
iNFTnews | 元宇宙为企业发展带来新思路
R语言(数值、列表、矩阵)上应用函数(sqrt、round、mean、log)、将矩阵所有数据求对数、就矩阵整体的均值、使用apply函数计算矩阵matrix的行均值、列均值、trim设置返回结果精度
非常菜的一个批量布置waf脚本
D. Districts Connection
一、根据系统架构定位系统性能瓶颈





![[uniapp applet] view container cover-view](/img/88/664b62c87b1540f204e8ea4a810657.png)



