按照父亲表示法题解来打的,80pts
# include <stdio.h>
# include <iostream>
using namespace std;
int dad[1000001];
int nodecount;
int maxdeep=1;
int deep[1000001];
int Find(int node)
{
if (deep[node] != 0) return deep[node] + 1;
deep[node] = Find(dad[node]);
return deep[node];
}
int main (void)
{
scanf ("%d",&nodecount);
for (int i=1;i<=nodecount;i++)
{
int a,b;
scanf ("%d %d",&a,&b);
dad[a] = dad[b] = i;
}
deep[1] = 1;
for (int i=2;i<=nodecount;i++)
{
maxdeep = max(Find(i),maxdeep);
}
printf("%d",maxdeep);
return 0;
}
在递归这一段
int Find(int node)
{
if (deep[node] != 0) return deep[node] + 1;
deep[node] = Find(dad[node]);
return deep[node];
}
将其改成题解中
int work(int x){ //递归函数,求节点 x 的深度
if(depth[x]!=0) //如果已经求出,就直接返回该深度
return depth[x] ;
if(fa[x]==0)
return depth[x] = 1;
//根节点直接返回 1
else
return depth[x] = 1 + work(fa[x]);
//非根节点返回它的前驱节点的深度加 1
}
就能A,自认为两段代码等价,错在哪?