hdu 3721 树的直径
思路:枚举+树的直径
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<cmath> #define clr(x,y) memset(x,y,sizeof(x)) #define Maxn 3000 #define inf 100000000 using namespace std; int head[Maxn],Max[Maxn],lMax[Maxn],id[Maxn],road[Maxn],e,n,ans,te; bool vi[Maxn]; struct Edge{ int u,v,next,val; }edge[Maxn*2]; void init() { clr(head,-1); clr(vi,0); clr(Max,0); clr(lMax,0); clr(road,0); clr(id,0); e=0; } void add(int u,int v,int val) { edge[e].u=u,edge[e].v=v,edge[e].val=val,edge[e].next=head[u],head[u]=e++; edge[e].u=v,edge[e].v=u,edge[e].val=val,edge[e].next=head[v],head[v]=e++; } void dfs(int u,int col,int fa) { int v,i; id[u]=col; for(i=head[u];i!=-1;i=edge[i].next){ v=edge[i].v; if(v==fa) continue; dfs(v,col,u); if(Max[v]+edge[i].val>Max[u]){ lMax[u]=Max[u]; Max[u]=Max[v]+edge[i].val; road[u]=v; } else if(Max[v]+edge[i].val>lMax[u]) lMax[u]=Max[v]+edge[i].val; } te=max(te,lMax[u]+Max[u]); } void predfs(int u,int d,int fa) { int v,i; Max[u]=max(Max[u],d); for(i=head[u];i!=-1;i=edge[i].next){ v=edge[i].v; if(v==fa) continue; if(road[u]==v) predfs(v,max(lMax[u],d)+edge[i].val,u); else predfs(v,max(Max[u],d)+edge[i].val,u); } } void solve() { int i,j,u,v,val,a,b; ans=inf; for(i=0;i<e-1;i+=2){ u=edge[i].u,v=edge[i].v,val=edge[i].val; clr(Max,0); clr(lMax,0); a=b=inf; te=0; dfs(u,0,v); predfs(u,0,v); dfs(v,1,u); predfs(v,0,u); for(j=1;j<=n;j++){ //cout<<j<<" "<<id[j]<<" "<<Max[j]<<endl; if(id[j]) a=min(a,Max[j]); else b=min(b,Max[j]); } ans=min(ans,max(a+b+val,te)); //cout<<a<<" "<<b<<" "<<val<<endl; // cout<<"******************"<<endl; } return ; } int main() { int i,j,u,v,val,t,Ca=0; scanf("%d",&t); while(t--){ init(); scanf("%d",&n); for(i=1;i<n;i++){ scanf("%d%d%d",&u,&v,&val); u++,v++; add(u,v,val); } solve(); printf("Case %d: %d\n",++Ca,ans); } return 0; }