hiho1050(树的直径)

题目连接:https://hihocoder.com/problemset/problem/1050

之前用过两边dfs求,这是另一种方法,记录每个点的最长路与次长路,不断更新。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn=100010;
 6 
 7 int md1[maxn],md2[maxn];
 8    //最长     次长
 9 struct node
10 {
11     int v;
12     int nex;
13 }e[maxn*2];
14 
15 
16 int head[maxn];
17 int cnt;
18 
19 void add(int u,int v)
20 {
21     e[cnt].v=v;
22     e[cnt].nex=head[u];
23     head[u]=cnt++;
24 }
25 
26 int dfs(int u,int pre)
27 {
28     int d;
29     for(int i=head[u];i!=-1;i=e[i].nex)
30     {
31         if(e[i].v==pre) continue;
32         d=dfs(e[i].v,u)+1;
33         if(d>md1[u])  //子树最长路大于父亲最长路径
34         {
35             md2[u]=md1[u];
36             md1[u]=d;
37         }
38         else if(d>md2[u]) md2[u]=d;  //子树路径只大于次长路径
39     }
40     return md1[u];
41 
42 }
43 int main()
44 {
45     int n;
46     int t;
47     while( scanf("%d",&n)!=EOF)
48     {
49         cnt=0;
50         int u,v;
51         memset(head,-1,sizeof(head));
52         memset(md1,0,sizeof(md1));
53         memset(md2,0,sizeof(md2));
54         for(int i=1;i<n;i++)
55         {
56             scanf("%d%d",&u,&v);
57             add(u,v);
58             add(v,u);
59         }
60         dfs(1,0);
61         int ans=0;
62         for(int i=1;i<=n;i++)
63             ans=max(ans,md1[i]+md2[i]);
64         printf("%d
",ans);
65     }
66 }
原文地址:https://www.cnblogs.com/yijiull/p/6710919.html