Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P3174 [HAOI2009] 毛毛虫

P3174 [HAOI2009] 毛毛虫

与一般的树的直径不同的是,本题还要加上与直径上的点相邻的点。提前处理一下每个点的度数,转移时加上即可。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 3e5 + 10, M = 6e5 + 10;
int n, m, ans, d[N], f[N];
int idx, hd[N], nxt[M], edg[M];
void dfs(int x)
{
f[x] = d[x] + 1;
int mx[2] = {0, 0};
for (int i = hd[x]; ~i; i = nxt[i])
{
if (f[edg[i]])
continue;
dfs(edg[i]);
if (f[edg[i]] > mx[0])
mx[1] = mx[0], mx[0] = f[edg[i]];
else if (f[edg[i]] > mx[1])
mx[1] = f[edg[i]];
f[x] = max(f[x], f[edg[i]] + d[x] - 1);
}
ans = max(ans, d[x] + 1 + (mx[1] ? (mx[1] - 2 + (mx[0] ? (mx[0] - 2) : 0)) : 0));
}
void add(int a, int b)
{
nxt[++idx] = hd[a];
hd[a] = idx;
edg[idx] = b;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
hd[i] = -1;
for (int a, b; m; m--)
{
scanf("%d%d", &a, &b);
add(a, b);
add(b, a);
d[a]++, d[b]++;
}
dfs(1);
printf("%d", ans);
return 0;
}