本题思路:读完题目之后,应该知道这道题求得是树的深度,同时记录深度最大时的孩子。用深搜即可。
下面是代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<vector<int>>man;
vector<int>small;
int sign;
int result = 0;
void dfs(int j,int cnt) {
if (result < cnt&&man[j].size() == 0) {
result = cnt;
small.clear(); //因为找到了比当前更深的,所以要清空之前的数据.
}
if (result == cnt)
small.push_back(j);
for (int i = 0; i < man[j].size(); i++) {
dfs(man[j][i],cnt+1);
}
}
int main() {
int num;
cin >> num;
man.resize(num+1);
for (int i = 1; i <= num; i++) {
int tmep;
cin >> tmep;
if (tmep == -1) {
sign = i;
continue;
}
man[tmep].push_back(i);
}
dfs(sign, 1);
cout << result << endl;
sort(small.begin(), small.end());
for (int i = 0; i < small.size(); i++) {
if (i != 0)
cout << " ";
cout << small[i];
}
system("pause");
}