小字辈
小字辈
比赛的时候心烦意乱,没有净下心来好好看题,导致没有看懂。遂考后又做了一遍,觉得方法很好
用的是并查集+路径优化
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int p[N], c[N];
int find(int x)
{
if(p[x] == -1)
{
return 1;
}
else
{
if(!c[x])//必须要加,不然会超时
c[x] = find(p[x]) + 1;
return c[x];
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for(int i = 1; i <= n; i++)
{
int m;
cin >> m;
p[i] = m;
}
int maxx = 0;
for(int i = 1; i <= n; i++)
{
c[i] = find(i);
maxx = max(maxx, c[i]);
}
cout << maxx << endl;
int res = 0, cnt = 0;
for(int i = 1; i <= n; i++)
if(maxx == c[i]) res++;//方便格式输出
for(int i = 1; i <= n; i++)
{
if(maxx == c[i])
{
cnt++;
cout << i << ((cnt == res) ? '\n' : ' ');
}
}
return 0;
}

浙公网安备 33010602011771号