一开始写的版本有三个数据点超时,之前回顾的时候以为是因为O(4*n),现在看来最有可能的是出在我的最后一次代码突破点上——在深度优先搜索的时候依旧是重复搜索了——尽管初始的时候没有重复,但如果没有判断是否已经有level值,会出现父结点重复搜索的情况。
中间的版本没有跳脱出第一个的整体框架但是也想方设法做了许多优化,难度刚好。
当然优化也是有作用的,比另外一位同学的结果普遍快——提交结果截图放在最后
有一个特殊样例是:1 -1 —— 嗯,全族只有一个人……
AC代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<cstring>
using namespace std;
#define maxn 1000005
typedef struct pp {
int no;
int f ;
int le ;
} pp;
pp x;
vector<pp> v;
vector<pp> ans;
int cp = 1;
int pbf(pp &y)
{
if (y.le > 0) return y.le;
if (y.f != -1)
{
y.le = pbf ( v[y.f] ) + 1;
if ( y.le >= cp )
{
if ( y.le > cp ) ans.clear();
cp = y.le ;
ans.push_back(y);
}
return y.le;
}
else
{
y.le = 1;
if ( y.le >= cp )
{
if ( y.le > cp ) ans.clear();
ans.push_back(y);
}
return 1;
}
}
int main()
{
int i, j, k, n, fir = 1;
x.le = 0;
v.push_back(x);
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
scanf("%d", &x.f);
x.no = i;
v.push_back(x);
}
for (i = 1; i <= n; ++i) if (!v[i].le) pbf(v[i]);
printf("%d\n", cp);
for (i = 0; i < ans.size(); ++i)
{
if (fir) fir = 0;
else printf(" ");
printf("%d", ans[i].no);
}
return 0;
}