【POJ1985】Cow Marathon

The diameter of the tree template title

After we keep drawing on this chart (tree) once dfs, define sum1 told his son to go the longest path from the current node is the number, sum2 indicate how many times a long path. We first with a time length of the current path + sum1 current path to a node of the current node sum2 update, if the update sum2 greater than sum1, then we exchange their values, this is not difficult to find the right, after completion of the calculation to us the current node's father returned to his sum1, so after ans answer is max (sum1 + sum2), this algorithm will traverse each point again, therefore, the time complexity is O (n).

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 int n,m;
 8 struct edge {
 9     int next,to,dis;
10 }a[100010<<1];
11 int num,head[100010<<1];
12 int f[100010],ans;
13 void add(int from,int to,int dis) {
14     a[++num].next=head[from];
15     a[num].to=to;
16     a[num].dis=dis;
17     head[from]=num;
18 }
19 int dfs(int u,int fa) {
20     int sum1=0,sum2=0;
21     for(int i=head[u];i;i=a[i].next)
22         if(a[i].to!=fa) {
23             sum2=max(sum2,dfs(a[i].to,u)+a[i].dis);
24             if(sum2>sum1) swap(sum1,sum2);
25             ans=max(ans,sum1+sum2);
26         }
27     return sum1;
28 }
29 int main() {
30     scanf("%d%d",&n,&m);
31     for(int i=1;i<=m;i++) {
32         char c;
33         int x,y,z;
34         cin>>x>>y>>z>>c;
35         add(x,y,z);
36         add(y,x,z);
37     }
38     dfs(1,0);
39     printf("%d\n",ans);
40     return 0;
41 }
AC Code

 

Guess you like

Origin www.cnblogs.com/shl-blog/p/10960990.html
Recommended