当前位置:网站首页>L2-026 小字辈 (25 分)
L2-026 小字辈 (25 分)
2022-06-29 09:23:00 【陌陌623】
本次刷题为2021年天梯
L2-026 小字辈 (25 分)
本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。
输入格式:
输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。
输出格式:
首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。
输入样例:
9
2 6 5 5 -1 5 6 4 7
输出样例:
4
1 9
题解
比较容易看出:
x是父 i是儿子
需要x添加儿子,原因是可能x有多个儿子
然后用bfs或者dfs求即可
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int n = 100005;
int N;
vector<int> v[n];
// BFS求
void bfs(int root)
{
// 首位是序号
// 次位是代数
queue<pair<int, int>> q;
q.push({root, 0});
// 最后的答案
vector<int> ans;
// 代数
int maxt = 0;
while (!q.empty())
{
auto x = q.front();
q.pop();
// 如果发现有更高代
// 则更新
if (maxt < x.second)
{
maxt = x.second;
ans.clear();
}
ans.push_back(x.first);
for (auto &e : v[x.first])
q.push({e, x.second + 1});
}
cout << maxt + 1 << endl;
int f = 0;
for (auto &e : ans)
{
if (f++ != 0)
cout << " ";
cout << e;
}
}
int main()
{
cin >> N;
int root = 0;
int x;
for (int i = 1; i <= N; i++)
{
cin >> x;
if (x == -1)
{
root = i;
continue;
}
v[x].push_back(i);
}
bfs(root);
return 0;
}
边栏推荐
- Using rancher to build kubernetes cluster
- Dsolve function of sympy
- 2019.10.27训练总结
- Causes and solutions of error reporting by using startactivity() method outside the activity
- Recyclerview refreshes blinks and crashes when deleting items
- 聊聊你理解的线程与并发
- 2019.10.30学习总结
- Caused by: org. apache. xerces. impl. io. MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8
- Summary of PHP memory horse technology research and killing methods
- 分布式和集群分不清,我们讲讲两个厨子炒菜的故事
猜你喜欢

Middle order traversal of Li Kou 94 binary tree

Using rancher to build kubernetes cluster

Constructing SQL statements by sprintf() function in C language

JVM之TLAB

弧形 View 和弧形 ViewPager

Dynamic linking of virtual machine stack of JVM

力扣94二叉树的中序遍历

How to traverse objects in the vector container

Application of keil5 integrated development environment for single chip microcomputer

Sixteen system counter and flow lamp
随机推荐
sublime text3设置运行自己的Makefile
2019-11-10训练总结
Gross Tumor Volume Segmentation for Head and Neck Cancer Radiotherapy using Deep Dense Multi-modalit
gSoap例子——calc
语言特性
JVM之对象的内存布局
Codeforces Round #641 Div2
在Activity外使用startActivity()方法报错原因与解决办法
Codeforces - 1151b thinking
详细分析PBot挖矿病毒家族行为和所利用漏洞原理,提供蓝军详细防护建议
Listview of the basic component of the shutter
Flutter 基础组件之 Image
使用Rancher搭建Kubernetes集群
EDA与VHDL题库
sympy的dsolve函数
2019.10.6训练总结
A 2.5D Cancer Segmentation for MRI Images Based on U-Net
leetcode MYSQL数据库题目180
ImageView picture fill problem
2019.10.20训练总结