poj2631
求一棵树的直径,所谓直径就是树上距离最远的两个点!
树形动归,每个点的为根的子树的最长向下链和次长链的和!
当然也可以二次深搜!
————————————————————————————————————————————————————
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<iostream> 5 using namespace std; 6 const int maxn=10010; 7 struct edge 8 { 9 int u,v,w,next; 10 }e[maxn<<1]; 11 int head[maxn],js; 12 long long ans; 13 long long ml[maxn],sl[maxn]; 14 void addage(int u,int v,int w) 15 { 16 e[++js].u=u;e[js].v=v;e[js].w=w; 17 e[js].next=head[u];head[u]=js; 18 } 19 void dfs(int u,int fa) 20 { 21 for(int i=head[u];i;i=e[i].next) 22 { 23 int v=e[i].v; 24 if(v!=fa) 25 { 26 dfs(v,u); 27 if(ml[v]+e[i].w>ml[u]) 28 { 29 sl[u]=ml[u]; 30 ml[u]=ml[v]+e[i].w; 31 } 32 } 33 else if(ml[v]+e[i].w>sl[u]) 34 sl[u]=ml[v]+e[i].w; 35 } 36 if(ml[u]+sl[u]>ans)ans=ml[u]+sl[u]; 37 } 38 int main() 39 { 40 int u,v,w; 41 while(scanf("%d%d%d",&u,&v,&w)==3) 42 { 43 addage(u,v,w); 44 addage(v,u,w); 45 } 46 dfs(1,0); 47 cout<<ans; 48 return 0; 49 }