【牛客小白月赛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 }
复制代码

 

posted @   liubilan  阅读(189)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示