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

分析:
跑两次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;
}

暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇