U81904 【模板】树的直径

1. 两次Dfs

注意:该方法无法解决负权树。

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
46
47
48
49
50
51
52
53
54
55
#include<cstdio>
#include<cstring>
#include<algorithm>
#define re register
using namespace std;
const int MAXn = 5e5;
const int MAXm = MAXn;
const int FINF = 0xc0c0c0c0;

int n;
int head[MAXn + 10], cntnex, nex[MAXm * 2 + 10], to[MAXm * 2 + 10], wei[MAXm * 2 + 10];
void Insert(int u, int v, int w) {
nex[++cntnex] = head[u];
head[u] = cntnex;
to[cntnex] = v;
wei[cntnex] = w;
}

int dis[MAXn + 10]; bool vis[MAXn + 10];
void Dfs(int cur) {
vis[cur] = 1;
for (re int i = head[cur]; i; i = nex[i]) {
if (vis[to[i]]) continue;
dis[to[i]] = dis[cur] + wei[i];
Dfs(to[i]);
}
}
int EvaFar(int root) {
memset(dis, 0xc0, sizeof(dis));
memset(vis, 0, sizeof(vis));
dis[root] = 0;
Dfs(root);
int mx = FINF, maxer = 0;
for (re int i = 1; i <= n; ++i) {
if (mx < dis[i]) {
mx = dis[i];
maxer = i;
}
}
return maxer;
}

int side1, side2;
int main() {
scanf("%d", &n);
for (re int i = 1, u, v, w; i < n; ++i) {
scanf("%d %d %d", &u, &v, &w);
Insert(u, v, w);
Insert(v, u, w);
}
side1 = EvaFar(1);
side2 = EvaFar(side1);
printf("%d %d\n", side1, side2);
printf("%d\n", dis[side2]);
}

2. 树形Dp

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
#include<bits/stdc++.h>
using namespace std;
const int MAXn = 5e5;
const int MAXm = MAXn;

template <typename T>
inline void read(T &a) {
char c;for (c = getchar(); (c < '0' || c > '9') && c != '-'; c = getchar());bool f = c == '-';T x = f ? 0 : (c ^ '0');for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {x = x * 10 + (c ^ '0');}a = f ? -x : x;
}
template <typename T, typename ...Argv>
inline void read(T &a, Argv &...argv) {
read(a), read(argv...);
}

int head[MAXn + 10], cntnex, nex[MAXm * 2 + 10], to[MAXm * 2 + 10], wei[MAXm * 2 + 10];
inline void Insert(int u, int v, int w) {
nex[++cntnex] = head[u];
head[u] = cntnex;
to[cntnex] = v;
wei[cntnex] = w;
}

int ans, d[MAXn + 10];
void Dfs(int cur, int fath) {
for (int i = head[cur]; i; i = nex[i]) {
if (to[i] == fath) continue;
Dfs(to[i], cur);
ans = max(ans, d[cur] + d[to[i]] + wei[i]);
d[cur] = max(d[cur], d[to[i]] + wei[i]);
}
}

int n;
signed main() {
read(n);
for (int i = 1, u, v, w; i < n; ++i) {
read(u, v, w);
Insert(u, v, w); Insert(v, u, w);
}
Dfs(1, 0);
printf("%d\n", ans);
return 0;
}