Links: http://hihocoder.com/problemset/problem/1224
Deep Search to find the maximum depth, from the maximum depth of the leaves back to the root of each vertex through the deep search for maximum depth
#include <iostream> #include <math.h> #include <stdio.h> #include <queue> #include <string.h > #include <algorithm>using namespace std;const int maxn=100000+10;struct node{int v,next;} edge[maxn];struct node{int start,step;} P[maxn];int head[maxn],vis[maxn],length[maxn],pre[maxn],temp,ldeepv;void Add (int u,int V,int index) {Edge[index].v=v ; Edge[index].next=head[u]; Head[u]=index;} void dfs (int v,int length)//seek maximum depth {if (temp<length) {temp=length; Ldeepv=v; } if (Vis[v]) return; Vis[v]=1; for (int i=head[v];i!=-1;i=edge[i].next) {if (!VIS[EDGE[I].V]) DFS (edge[i].v,length+1); }}int Main () {int n; while (~SCANF ("%d", &n)) {int a,b,cnt=0; memset (head,-1,sizeof (head)); memset (length,0,sizeof (length)); memset (pre,0,sizeof (pre)); for (int i=1;i<n;i++) {scanf ("%d%d", &a,&b); Add (a,b,i); Pre[b]=a; } ldeepv=temp=0; DFS (1,0); Length[cnt++]=temp; Deposit Length//printf ("%d\n", temp); int K=LDEEPV; memset (vis,0,sizeof (VIS)); while (pre[k]!=0)//backtracking {vis[k]=1; K=PRE[K]; Temp=0; DFS (k,0); Length[cnt++]=temp; } sort (length,length+cnt); printf ("%d\n", Length[cnt-1]+length[cnt-2]); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hihocoder 1224: Racing