当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Automatic Multi-Organ SegmVentation on Abdominal CT With Dense V-Networks

Middle order traversal of Li Kou 94 binary tree

JVM之TLAB

另类实现 ScrollView 下拉头部放大

HDU 6778 Car (分组枚举-->状压 dp)

Zabbix4.4 configure the indicators of the monitoring server and solve the garbled graphics pages

GridView of basic component of shutter

任务调度器之Azkaban的使用

Nacos环境隔离

Flutter 基础组件之 Image
随机推荐
leetcode MYSQL数据库题目177
Summary of PHP memory horse technology research and killing methods
图片验证码控件
Codeforces Round #659 (Div. 2)
Force deduction 85 question maximum rectangle
数据库常见面试题(附答案)
Alibaba cloud firewall configuration, multiple settings (iptables and firewall)
弧形 View 和弧形 ViewPager
Leetcode MySQL database topic 178
2019.11.20训练总结
Pointer functions and function pointers
Sublime Text3 set to run your own makefile
Gross Tumor Volume Segmentation for Head and Neck Cancer Radiotherapy using Deep Dense Multi-modalit
JS obtain mobile phone model and system version
Flutter 基础组件之 GridView
manacher
gcc与makefile
JVM instructions for four call methods
Codeforces Round #657 Div. 2
Codeforces - 1151b thinking