#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
vector<int> v[N];
map<int, vector<int>> mp;
void dfs(int x, int h)
{
mp[h].push_back(x);
for (auto c : v[x])
dfs(c, h + 1);
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
if (x == -1)
x = 0;
v[x].push_back(i);
}
dfs(0, 1);
int MAX_h = mp.rbegin()->first;
cout << MAX_h - 1 << endl;
for (int i = 0; i < mp[MAX_h].size(); i++)
{
if (i) cout << ' ';
cout << mp[MAX_h][i];
}
return 0;
}
或
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
vector<int> v[N];
vector<int> num;
int MAX_h;
void dfs(int x, int h)
{
if (h > MAX_h)
{
MAX_h = h;
num.clear();
}
if (h == MAX_h) num.push_back(x);
for (auto c : v[x]) dfs(c, h + 1);
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
if (x == -1) x = 0;
v[x].push_back(i);
}
dfs(0, 1);
cout << MAX_h - 1 << endl;
for (int i = 0; i < num.size(); i++)
{
if (i) cout << ' ';
cout << num[i];
}
return 0;
}