【牛客小白月赛6】 C 桃花 - 树上最长路

题目地址:https://www.nowcoder.com/acm/contest/136/C

 

dfs找出最长路和次长路,将两个结果相加再加上起点即可;

 1 #include<iostream>
 2 using namespace std;
 3 
 4 const int N = 1e6+5;
 5 struct EDGE {
 6     int to, pre;
 7 }edge[2*N];
 8 int n, tot=1, head[N], first[N], second[N], ans=0;
 9 
10 void read(int &x) {
11     int f = 1; x = 0;
12     char ch = getchar();
13    
14     while (ch < '0' || ch > '9')   {if (ch == '-') f = -1; ch = getchar();}
15     while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
16     x *= f;
17 }
18 
19 void add_edge(int a, int b)
20 {
21     edge[tot].to = b;
22     edge[tot].pre = head[a];
23     head[a] = tot++;
24 }
25 
26 void dfs(int k, int pre)
27 {
28     for(int i=head[k]; i; i=edge[i].pre) {
29         int to = edge[i].to;
30         if(to == pre) continue;
31         
32         dfs(to, k);
33         if(first[k] < first[to]+1) {
34             second[k] = first[k];
35             first[k] = first[to]+1;
36         }
37         else
38             second[k] = max(second[k], first[to]+1);
39     }
40     ans = max(ans, first[k]+second[k]);
41 }
42 
43 int main()
44 {
45     read(n);
46     for(int a,b,i=1; i<n; i++) {
47         read(a); read(b);
48         add_edge(a,b);
49         add_edge(b,a);
50     }
51     
52     dfs(1, 0);
53     cout<<ans+1<<endl;
54     
55     return 0;
56 }

 

转载于:https://www.cnblogs.com/liubilan/p/9520605.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值