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 100 101 102 103
| #include <cstdio> #include <set> using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type, class ...rest> void read (Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } typedef long long LL; const int N = 1e5 + 10, M = 2e5 + 10; LL ans, s[N]; int idx, hd[N], nxt[M], edg[M], wt[M]; int n, m, d[N], p[N], sz[N]; int stmp, dfn[N], rnk[N], son[N], top[N]; void dfs1 (int x = 1) { sz[x] = 1; for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] ^ p[x]) { p[edg[i]] = x; d[edg[i]] = d[x] + 1; s[edg[i]] = s[x] + wt[i]; dfs1(edg[i]); sz[x] += sz[edg[i]]; if (sz[edg[i]] > sz[son[x]]) son[x] = edg[i]; } } void dfs2 (int x = 1, int t = 1) { top[x] = t; rnk[dfn[x] = ++stmp] = x; if (!son[x]) return; dfs2(son[x], t); for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] ^ p[x] && edg[i] ^ son[x]) dfs2(edg[i], edg[i]); } int lca (int a, int b) { while (top[a] ^ top[b]) { if (d[top[a]] < d[top[b]]) swap(a, b); a = p[top[a]]; } if (d[a] > d[b]) swap(a, b); return a; } void add (int a, int b, int c) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; } LL dis (int a, int b) { if (a == 0 || b == 0 || a == n + 1 || b == n + 1) return 0; a = rnk[a], b = rnk[b]; int t = lca(a, b); return s[a] + s[b] - 2 * s[t]; } int main () { read(n, m); for (int i = 1; i <= n; ++i) hd[i] = -1; for (int i = 1, a, b, c; i < n; ++i) read(a, b, c), add(a, b, c), add(b, a, c); dfs1(), dfs2(); set <int> c; c.insert(0), c.insert(n + 1); for (int t; m; --m) { read(t); t = dfn[t]; int a = *--c.lower_bound(t), b = *c.upper_bound(t); if (c.count(t)) { ans -= dis(a, t) + dis(b, t) - dis(a, b); c.erase(t); } else { ans += dis(a, t) + dis(b, t) - dis(a, b); c.insert(t); } write(ans + dis(*++c.begin(), *----c.end())), puts(""); } return 0; }
|