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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
| #include <iostream>
#include <cstdio>
#include <set>
using namespace std;
const int INF = 1<<30;
typedef long long LL;
int getint() {
int r = 0, k = 1; char c = getchar();
for (; '0' > c || c > '9'; c = getchar()) if (c == '-') k = -1;
for (; '0' <= c && c <= '9'; c = getchar()) r = r * 10 - '0' + c;
return r * k;
}
set<int> S;
set<int>::iterator it, fst, lst;
int N, M;
int tot = 0;
bool have[100005];
struct edge_type {
int to, next, len;
} edge[200005];
int h[100005], cnte = 1;
void ins(int u, int v, int w) {
edge[++cnte].to = v;
edge[cnte].next = h[u];
edge[cnte].len = w;
h[u] = cnte;
edge[++cnte].to = u;
edge[cnte].next = h[v];
edge[cnte].len = w;
h[v] = cnte;
}
int fa[100005], dep[100005], siz[100005], son[100005], top[100005], dfn[100005], dfsclock = 0, ddfn[100005];
LL dis[100005];
int dfs1(int now, int father, int deep, LL ndis) {
dfn[now] = ++dfsclock; ddfn[dfsclock] = now;
fa[now] = father; dep[now] = deep; dis[now] = ndis;
siz[now] = 1; son[now] = 0;
for (int i = h[now]; i; i = edge[i].next) {
if (edge[i].to == father) continue;
siz[now] += dfs1(edge[i].to, now, deep + 1, ndis+edge[i].len);
if (siz[son[now]] < siz[edge[i].to]) son[now] = edge[i].to;
}
return siz[now];
}
void dfs2(int now, int father, int tp) {
top[now] = tp;
if (son[now]) {
dfs2(son[now], now, tp);
for (int i = h[now]; i; i = edge[i].next) {
if (edge[i].to == father || edge[i].to == son[now]) continue;
dfs2(edge[i].to, now, edge[i].to);
}
}
}
int lca(int u, int v) {
while (top[u] != top[v]) {
if (dep[top[u]] < dep[top[v]]) swap(u, v);
u = fa[top[u]];
}
if (dep[u] > dep[v]) swap(u, v);
return u;
}
LL dist(int u, int v) { return dis[u] + dis[v] - (dis[lca(u, v)] << 1); }
int main() {
N = getint(); M = getint();
int x,y,z;
for (int i=1;i<N;++i) {
x = getint();y=getint(); z = getint();
ins(x, y, z);
}
dfs1(1, 0, 1, 0);
dfs2(1, 0, 1);
LL ans = 0;
for (int i = 0; i < M; ++i) {
x = getint();
x = dfn[x];
if (have[x]) {
have[x] = false;
it = S.find(x);
--tot;
if (tot) {
lst = it; if (lst == S.begin()) lst = S.end(); --lst;
fst = it; ++fst; if (fst == S.end()) fst = S.begin();
ans = ans - dist(ddfn[x], ddfn[*lst]) - dist(ddfn[x], ddfn[*fst]) + dist(ddfn[*fst], ddfn[*lst]);
}
S.erase(it);
} else {
have[x] = true;
it = (S.insert(x)).first;
if (tot) {
lst = it; if (lst == S.begin()) lst = S.end(); --lst;
fst = it; ++fst; if (fst == S.end()) fst = S.begin();
ans = ans + dist(ddfn[x], ddfn[*lst]) + dist(ddfn[x], ddfn[*fst]) - dist(ddfn[*fst], ddfn[*lst]);
}
++tot;
}
printf("%lld\n", ans);
}
}
|