# 【HDU3721】枚举+最长路

1.u的左子树的直径；

2.v的右子树的直径；

3.u的左子树的直径上中点分割的最长路径 +  v的右子树的直径上中点分割的最长路径 + 边权

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define N 3000
void ini()
{
cnt=0;
}
struct Edge
{
int next,w,to;
}e[N*2];
void Add_edge(int a, int b, int c)
{
e[cnt].to=b;e[cnt].w=c;
}
int dis1[N],dis2[N],fa2[N],vis[N],fa1[N],max_dis,max_id;
void BFS(int root, int dis[], int fa[])
{
max_dis=0;max_id=root;fa[root]=root;
memset(vis,0,sizeof(vis));
dis[root]=0;
queue <int> Q;
Q.push(root);
while(!Q.empty())
{
int u=Q.front();Q.pop();
vis[u]=1;
for(int i = head[u]; i != -1; i = e[i].next)
{
int v=e[i].to;
if(vis[v])continue;
dis[v]=dis[u]+e[i].w;
if(max_dis<dis[v]){max_dis=dis[v],max_id=v;}
fa[v]=u;
Q.push(v);
}
}
}
void dfs(int u, int pre, int dis[]) //dis1==s为起点  dis2==t为起点
{
for(int i = head[u]; i != -1; i = e[i].next)
{
int v=e[i].to;
if(v==pre)continue;
dfs(v,u,dis);
if(max_dis<dis[v]){max_dis=dis[v];max_id=v;}
}
}
int main()
{
int T;scanf("%d",&T);
for(int g = 1; g <= T; g++)
{
ini();
int n;scanf("%d",&n);
for(int i = 1; i < n; i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
}
int s=0,t;
BFS(s,dis1,fa1);
s=max_id;
BFS(s,dis1,fa1);
t=max_id;
BFS(t,dis2,fa2);
int ans=0x7fffffff;
for(int i = t; i != s; i=fa1[i])
{
int tmp_ans;
int len=dis2[fa1[i]]-dis2[i];
max_dis=dis2[i];
max_id=i;
dfs(i,fa1[i],dis2);
tmp_ans=max_dis;
int top=max_dis/2;
int zhongdian,max1,max2;
int tmp=0x7fffffff;
zhongdian=max_id;
for(int j = max_id; j != t; j=fa2[j])
if(abs(dis2[j]-top)<tmp){tmp=abs(dis2[j]-top);zhongdian=j;}
max1=max(dis2[max_id]-dis2[zhongdian],dis2[zhongdian]);
max_dis=dis1[fa1[i]];
max_id=fa1[i];
dfs(fa1[i],i,dis1);
tmp_ans=max(tmp_ans,max_dis);
top=max_dis/2;
tmp=0x7fffffff;
zhongdian=max_id;
for(int j = max_id; j != s; j=fa1[j])
if(abs(dis1[j]-top)<tmp){tmp=abs(dis1[j]-top);zhongdian=j;}
max2=max(dis1[max_id]-dis1[zhongdian],dis1[zhongdian]);
tmp_ans=max(tmp_ans,max1+max2+len);
ans=min(ans,tmp_ans);
}
printf("Case %d: %d\n",g,ans);
}
return 0;
}


08-12 56
08-12 59

08-11 200
01-13 161
07-05 962
09-21 386
08-05 1682
12-02 1082
04-10 1802