对树的直径的讲解
http://hihocoder.com/problemset/problem/1050
http://blog.csdn.net/fjsd155/article/details/6917291
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f
#define fi first
#define se second
#define mem(a,b) memset((a),(b),sizeof(a))
const LL MAXV=100000+3;
struct Edge//边
{
LL to,cost;
Edge(LL t,LL c):to(t),cost(c){}
};
LL N,L,V1,V2,ans;
vector<Edge> G[MAXV];//邻接表存树
LL dp[MAXV],deep[MAXV],dis[2][MAXV];
void init()//初始化
{
for(LL i=1;i<=N;++i)
{
G[i].clear();
dp[i]=0;
deep[i]=i;
}
L=0;
ans=0;
}
void dfs(LL u,LL f)
{
LL v1 = u,v2 = u;
LL first = 0 , second = 0;
for(int i = 0 ; i < G[u].size() ; ++i)
{
LL v = G[u][i].to;
if( v== f )continue;
dfs( v,u );
LL now_dis=dp[v]+G[u][i].cost;
if(now_dis>first)
{
second=first;
v2=v1;
first=now_dis;
v1=deep[v];
}
else if(now_dis>second)
{
second=now_dis;
v2=deep[v];
}
}
dp[u] = first;
deep[u] = v1;
if(first+second>L){
L=first+second;
V1=v1;
V2=v2;
}
}
int main()
{
while(~scanf("%lld",&N))
{
init();
for(LL i=0;i<N-1;++i)
{
LL a,b,c;
scanf("%lld%lld",&a,&b);
G[a].push_back(Edge(b,1));
G[b].push_back(Edge(a,1));
}
dfs(1,-1);
cout << L << endl;
}
return 0;
}