Luogu P3320 [SDOI2015]寻宝游戏

题目描述

https://www.luogu.com.cn/problem/P3320

Solution

注意到遍历这些关键点的最短距离就是按照 $dfs$ 序走一遍

我们用 $set$ 维护一下就行了

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <cstdio>
#include <set>
#define maxn 100010
#define ll long long
using namespace std;

int n, m;

struct Edge {
int to, next, w;
} e[maxn * 2]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

int f[maxn][21], dep[maxn], id[maxn], c2; ll dis[maxn];
void dfs(int u, int fa) {
id[u] = ++c2;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w; if (v == fa) continue;
f[v][0] = u; dep[v] = dep[u] + 1; dis[v] = dis[u] + w;
dfs(v, u);
}
}

void init_lca() {
for (int j = 1; j <= 20; ++j)
for (int i = 1; i <= n; ++i) f[i][j] = f[f[i][j - 1]][j - 1];
}

int get_lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
for (int i = 20; ~i; --i)
if (dep[f[x][i]] >= dep[y]) x = f[x][i];
if (x == y) return x;
for (int i = 20; ~i; --i)
if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i];
return f[x][0];
}

inline ll D(int x, int y) {
if (!x || y == n + 1) return 0;
return dis[x] + dis[y] - 2 * dis[get_lca(x, y)];
}

struct cmp {
bool operator () (const int &u, const int &v) { return id[u] < id[v]; }
};

int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m;
for (int i = 1; i < n; ++i) {
int x, y, z; cin >> x >> y >> z;
add_edge(x, y, z); add_edge(y, x, z);
} dep[1] = 1; dfs(1, 0); init_lca(); id[0] = 0; id[n + 1] = n + 1;
set<int, cmp> S; S.insert(0); S.insert(n + 1);
ll ans = 0;
for (int i = 1; i <= m; ++i) {
int x; cin >> x;
auto l = S.lower_bound(x), r = S.upper_bound(x);
if (*l == x) {
--l; ans += D(*l, *r) - D(*l, x) - D(x, *r);
S.erase(x);
}
else {
--l; ans += D(*l, x) + D(x, *r) - D(*l, *r);
S.insert(x);
}
cout << ans + D(*++S.begin(), *----S.end()) << "\n";
}
return 0;
}