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 @ 2022-03-22 15:39  Xxaj5  阅读(22)  评论(0编辑  收藏  举报