# L2-026. 小字辈

400 ms

65536 kB

8000 B

Standard

9
2 6 5 5 -1 5 6 4 7

4
1 9

题意和功夫传人那个差不多，就是给你N个人的父亲是哪个，祖先的父亲用-1来表示，然后查询你辈分最小的是第几辈儿，并且输出那些辈分的人。

#include <bits/stdc++.h>

using namespace std;

vector < vector<int> > v;
queue<int>q;
struct node {
int id,beifen;
} fa[100020];

bool cmp(struct node  a,struct node b) {
if(a.beifen == b.beifen)
return a.id < b.id;
return a.beifen > b.beifen;
}
int main() {
int y,n,cnt = 0,id = 0;
scanf("%d",&n);
v.resize(n + 2);
for(int i = 1; i <= n; i++) {
scanf("%d",&y);
if(y == -1) v[0].push_back(i),fa[i].beifen = 1;
else  v[y].push_back(i);
}
q.push(0);
while(!q.empty()) {
int x = q.front();
q.pop();
for(int i = 0; i < v[x].size(); i++)
fa[v[x][i]].beifen = fa[x].beifen + 1,q.push(v[x][i]);
}
for(int i = 0; i <= n; i++)
fa[i].id = i;
sort(fa + 1,fa + n + 1,cmp);
cout << fa[1].beifen << endl;
id = fa[1].beifen;
for(int i = 1; i <= n; i++)
if(id == fa[i].beifen)  cnt++;
else                    break;
for(int i = 1; i <= cnt; i++)
printf("%d%c",fa[i].id,i == cnt? '\n':' ');
return 0 ;
}