Cow Marathon

poj1985:http://poj.org/problem?id=1985

题意:就是树的直径。

题解:直接DFS即可。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<vector>
 6 using namespace std;
 7 const int N=1e5+10;
 8 struct Node{
 9    int v;
10    int w;
11 };
12 vector<Node>Q[N];
13 int n,m,k,u,v;
14 int maxn,start;
15 void DFS(int u,int f,int len){
16     if(len>maxn){
17         maxn=len;
18         start=u;
19     }
20     for(int i=0;i<Q[u].size();i++){
21         if(f!=Q[u][i].v){
22             DFS(Q[u][i].v,u,len+Q[u][i].w);
23         }
24     }
25 }
26 int main(){
27     while(~scanf("%d%d",&n,&m)){
28          for(int i=1;i<=n;i++)
29              Q[i].clear();
30          for(int i=1;i<=m;i++){
31             scanf("%d %d %d",&u,&v,&k);
32             getchar();getchar();
33             Node temp;temp.v=v;temp.w=k;
34             Q[u].push_back(temp);
35             temp.v=u;temp.w=k;
36             Q[v].push_back(temp);
37          }
38         start=0,maxn=0;
39          DFS(1,0,0);
40          maxn=0;
41          DFS(start,0,0);
42       printf("%d\n",maxn);
43 
44     }
45 }
View Code

 

posted on 2014-08-16 09:27  天依蓝  阅读(114)  评论(0编辑  收藏  举报

导航