题目描述
思路
一本通的描述比较详细
比较好的博客
代码
#include
#include
#include
#include
#define FOR(a, n) for(int i = 1; i <= (n); ++i)
using namespace std;
const int MAX = 1e5 + 5;
int n, m;
long long ans;
int head[MAX], ver[MAX << 1], edge[MAX << 1], nt[MAX << 1], ht; // 存储边相关
int dfn[MAX], cnt; // dfn序相关
int f[MAX][21], dep[MAX]; // lca相关
long long dist[MAX];
set > st;
set >::iterator it;
void add(int x, int y, int z) {
nt[++ht] = head[x], head[x] = ht, ver[ht] = y, edge[ht] = z;
}
void dfs_lca(int x, int u, int z) {
dep[x] = dep[u] + 1;
dfn[x] = ++cnt;
dist[x] = dist[u] + z;
f[x][0] = u;
for (int i = 1; i < 21; ++i) {
f[x][i] = f[f[x][i - 1]][i - 1];
}
for (int i = head[x], j, k; i; i = nt[i]) {
j = ver[i], k = edge[i];
if (j == u) continue;
dfs_lca(j, x, k);
}
}
int lca(int x, int y) {
int X = x, Y = y;
if (dep[x] < dep[y]) swap(x, y);
for (int i = 20; i >= 0; --i) {
if (dep[f[x][i]] >= dep[y]) {
x = f[x][i];
}
}
if (x == y) return x;
for (int i = 20; i >= 0; --i) {
if (f[x][i] != f[y][i]) {
x = f[x][i], y = f[y][i];
}
}
// printf("lca: %d %d %d\n", X, Y, f[x][0]);
return f[x][0];
}
long long path(int x, int y) {
return dist[x] + dist[y] - (dist[lca(x, y)] << 1);
}
inline int read() {
int s = 0;
char ch = getchar();
while (ch < '0' || ch > '9') ch = getchar();
while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s;
}
void show() {
printf("%d %d\n", n, m);
puts("dep:");
FOR(dep, n) printf("%d ", dep[i]); puts("");
puts("dfn");
FOR(dfn, n) printf("%d ", dfn[i]); puts("");
puts("dist");
FOR(dist, n) printf("%lld ", dist[i]); puts("");
puts("fa");
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < 4; j++) {
printf("%d ", f[i][j]);
}
puts("");
}
}
int main() {
n = read();
for (int i = 1, a, b, c; i < n; ++i) {
a = read(), b = read(), c = read();
add(a, b, c), add(b, a, c);
}
m = read();
dfs_lca(1, 0, 0);
// show();
char ch[5];
for (int i = 1, j; i <= m; ++i) {
scanf("%s", ch);
// puts(ch);
pair l, r, te;
if (strcmp(ch, "+") == 0) {
j = read();
te = make_pair(dfn[j], j);
if (st.size() != 0) { // 从第二个点开始计算ans的值
it = (st.lower_bound(te));
if (it == st.begin()) it = st.end();
l = *(--it);
// printf("L +: %d %d\n", l.first, l.second);
it = st.upper_bound(te);
if (it == st.end()) r = *st.begin();
else r = *it;
// printf("R +: %d %d\n", r.first, r.second);
ans = ans - path(l.second, r.second) + path(l.second, j) + path(r.second, j);
}
st.insert(make_pair(dfn[j], j)); // 第一个点直接插入
} else if (strcmp(ch, "-") == 0) {
j = read();
te = make_pair(dfn[j], j);
st.erase(te);
if (st.size() == 0) { // 删除最后一个点之后,直接返回
ans = 0;
continue;
}
it = st.lower_bound(te); // 剩余点超过0个,要重新计算ans的值
if (it == st.begin()) it = st.end();
l = *(--it);
// printf("L -: %d %d\n", l.first, l.second);
it = st.upper_bound(te);
if (it == st.end()) r = *st.begin();
else r = *it;
// printf("R -: %d %d\n", r.first, r.second);
ans = ans + path(l.second, r.second) - path(l.second, j) - path(r.second, j);
} else {
printf("%lld\n", ans / 2);
}
}
return 0;
}