CodeForces 116C 【BFS】
思路:
求所有树的最大高度?
注意:所有树从树根开始?
#include <bits/stdc++.h> using namespace std; typedef long long LL; struct asd{ int to; int next; }e[2500]; int head[2500],tol; int pre[2500]; int n; void add(int u,int v) { e[tol].to=v; e[tol].next=head[u]; head[u]=tol++; } bool vis[2500]; struct ad{ int w; int step; }; int BFS(int s) { int res=0; vis[s]=1; ad now,nex; now.step=1; now.w=s; queue<ad>q; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); res=max(now.step,res); int u=now.w; for(int i=head[u];~i;i=e[i].next) { int v=e[i].to; if(vis[v]) continue; vis[v]=1; nex.w=v; nex.step=now.step+1; q.push(nex); } } return res; } int main() { int x; scanf("%d",&n); tol=0; memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); memset(pre,0,sizeof(pre)); for(int i=1;i<=n;i++) { scanf("%d",&x); if(x==-1) continue; add(x,i); pre[i]++; } int ans=0; for(int i=1;i<=n;i++){ if(!pre[i]) { ans=max(ans,BFS(i)); } } printf("%d\n",ans); return 0; }