POJ 1985
求一棵树内最远的两点,DFS,顺便记录以某节点为根内最远的两点的距离,返回最远点的距离。其实是DP。
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <cctype> 5 #include <algorithm> 6 #define LL unsigned __int64 7 using namespace std; 8 9 const int N= 111000; 10 11 struct Edge{ 12 int u,v,c; 13 int next; 14 }edge[N]; 15 int head[N],n,m,tot,ans; 16 17 void addedge(int u,int v,int c){ 18 edge[tot].u=u; 19 edge[tot].v=v; 20 edge[tot].c=c; 21 edge[tot].next=head[u]; 22 head[u]=tot++; 23 } 24 25 int dfs(int u,int f){ 26 int max1=0,max2=0,v,tmp; 27 for(int e=head[u];e!=-1;e=edge[e].next){ 28 v=edge[e].v; 29 if(v!=f){ 30 tmp=edge[e].c; 31 tmp+=dfs(v,u); 32 if(tmp>max1){ 33 max2=max1; 34 max1=tmp; 35 } 36 else if(tmp>max2){ 37 max2=tmp; 38 } 39 } 40 } 41 if(max1+max2>ans) 42 ans=max1+max2; 43 return max1; 44 } 45 46 int main(){ 47 int u,v,c; char t; 48 while(scanf("%d%d",&n,&m)!=EOF){ 49 tot=0; ans=0; 50 memset(head,-1,sizeof(head)); 51 for(int i=1;i<=m;i++){ 52 scanf("%d %d %d %c",&u,&v,&c,&t); 53 // cout<<u<<v<<c<<endl; 54 addedge(u,v,c); 55 addedge(v,u,c); 56 } 57 dfs(1,-1); 58 printf("%d\n",ans); 59 } 60 return 0; 61 }