L2-026 小字辈

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 100010;

vector<int> g[N];

int main() {
    int n;
    cin >> n;
    int root = -1;
    for (int i = 1; i <= n; i++) {
        int x;
        cin >> x;
        if (x == -1) root = i;
        else g[x].push_back(i);
    }   

    vector<int> depth(n + 1, 0);
    function<void(int)> bfs = [&] (int root) {
        queue<int> q;
        q.push(root);
        depth[root] = 1;

        while (q.size()) {
            int u = q.front();
            q.pop();
        
            for (auto &v : g[u]) {
                q.push(v);
                depth[v] = depth[u] + 1;
            }
        }
    };
    
    bfs(root);
    
    int mx = *max_element(depth.begin() + 1, depth.end());
    vector<int> res;
    for (int i = 1; i <= n; i++) {
        if (depth[i] == mx) res.push_back(i);
    }
    cout << mx << "\n";
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << " "[i == res.size() - 1];
    }

    return 0;
}
posted @   Xxaj5  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2020-03-22 暴力+分治+贪心+DP:最大子序列和
2020-03-22 (Good topic)四因数 (leetcode 181周赛T2)
2020-03-22 按既定顺序创建目标数组 (leetcode181周赛T1)
2020-03-22 排序:使数组唯一的最小增量 (3.22 leetcode每日打卡)
2020-03-22 (Good topic)字符串的最大公因子 (3.21leetcode每日打卡)
点击右上角即可分享
微信分享提示