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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| #include <iostream> #include <cstdio> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <cmath> using namespace std; typedef long long ll; const int Maxn = 2e5+5;
int Next[Maxn], head[Maxn], ver[Maxn], edge[Maxn], dfn[Maxn], f[Maxn][30], d[Maxn], a[Maxn]; int x, y, z, n, m, tot, t; ll dis[Maxn], ans; char ch[5];
void bfs() { queue <int> q; q.push(1); d[1] = 1; while(q.size()) { int x = q.front(); q.pop(); for(int i = head[x]; i; i = Next[i]) { int y = ver[i]; if(d[y]) continue; d[y] = d[x] + 1; q.push(y); f[y][0] = x; dis[y] = dis[x] + edge[i]; for(int j = 1; j <= t; j++){ f[y][j] = f[f[y][j-1]][j-1]; } } } }
int cnt; void dfs(int x) { dfn[x] = ++cnt; a[cnt] = x; for(int i = head[x]; i; i = Next[i]) { int y = ver[i]; if(dfn[y]) continue; dfs(y); } } void add(int x, int y, int z) { ver[++tot] = y; Next[tot] = head[x]; head[x] = tot; edge[tot] = z; } int lca(int x, int y) { if(d[x] > d[y]) swap(x, y); for(int i = t; i >= 0; i--){ if(d[f[y][i]] >= d[x]) y = f[y][i]; } if(x == y) return x; for(int i = t; i >= 0; i--) { if(f[x][i] != f[y][i]) x = f[x][i], y = f[y][i]; } return f[x][0]; }
ll path(int x, int y) { return dis[x] + dis[y] - 2 * dis[lca(x, y)]; }
set <int> s; typedef set <int> :: iterator It; It it;
It L(It it) { if(it == s.begin()) return --s.end(); return --it; }
It R(It it) { if(it == --s.end()) return s.begin(); return ++it; } int main() { scanf("%d", &n); t = (int)(log(n) / log(2)) + 1; for(int i = 1; i < n; i++) { scanf("%d%d%d", &x, &y, &z); add(x, y, z); add(y, x, z); } dfs(1); bfs(); scanf("%d", &m); for(int i = 1; i <= m; i++) { scanf("%s", ch); if(ch[0] == '+') { scanf("%d", &x); if(s.size()) { it = s.upper_bound(dfn[x]); if(it == s.end()) it = s.begin(); int l = *L(it), r = *it; ans += path(a[l], x) + path(x, a[r]) - path(a[l], a[r]); } s.insert(dfn[x]); } else if(ch[0] == '-') { scanf("%d", &x); it = s.find(dfn[x]); int l = *L(it), r = *R(it); ans -= path(x, a[l]) + path(x, a[r]) - path(a[l], a[r]); s.erase(dfn[x]); } else { printf("%lld\n", ans/2); } } return 0; }
|