[ural 2119]. Tree Hull

题意

给出一棵树,初始点集(S)为空,每次操作加入一个点到(S)中或从(S)中删除一个点,询问一个树上的最小的能覆盖(S)中所有点的连通块的边权和。
(n, q leq 3e5)

题解

很像个虚树的模型,但是很遗憾,虚树太逊了,是离线算法。
但是考虑到每次加点/删点,增加/减少的贡献好像并不复杂,所以可以直接用dfs序做。
用加点来举例子。每当要加入一个点(x),我们找到点集(S)中dfs序与(x)相邻的两个点(一前一后),设为(p)(q)
(x)(p leftrightarrow q)的路径上没有其他(S)中的点,而我们要加入的贡献就是(x)(p leftrightarrow q)这条路径的距离。
距离为

[len[x] - len[lca(x, p)] - len[lca(x, q)] + len[lca(p, q)] ]

注意如果找不到(p)或找不到(q)的话要特殊处理。
复杂度(mathcal O((n + q) log n))

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 3e5 + 5, H = 18;
int n, q, tot, times; ll ans;
int lnk[N], nxt[N << 1], son[N << 1], w[N << 1];
int id[N], dfn[N], dep[N], fa[N][H]; ll len[N];
set <int> s;
void add (int x, int y, int z) {
	nxt[++tot] = lnk[x], lnk[x] = tot, son[tot] = y, w[tot] = z;
}
void dfs (int x, int p) {
	id[dfn[x] = ++times] = x, dep[x] = dep[p] + 1, fa[x][0] = p;
	for (int i = 1; i < H; ++i) {
		fa[x][i] = fa[fa[x][i - 1]][i - 1];
	}
	for (int j = lnk[x], y; j; j = nxt[j]) {
		y = son[j];
		if (y != p) {
			len[y] = len[x] + w[j];
			dfs(y, x);
		}
	}
}
int lca (int x, int y) {
	if (dep[x] < dep[y]) {
		swap(x, y);
	}
	int dif = dep[x] - dep[y];
	for (int i = H - 1; ~i; --i) {
		if (dif >> i & 1) {
			x = fa[x][i];
		}
	}
	if (x == y) {
		return x;
	}
	for (int i = H - 1; ~i; --i) {
		if (fa[x][i] != fa[y][i]) {
			x = fa[x][i], y = fa[y][i];
		}
	}
	return fa[x][0];
}
ll calc (int x) {
	int p = *(--s.lower_bound(dfn[x]));
	int q = *s.upper_bound(dfn[x]);
	if (dfn[x] < *s.begin()) {
		return len[q] - len[x];
	} else
	if (dfn[x] > *(--s.end())) {
		return len[x] - len[p];
	} else {
		return len[x] - len[lca(x, id[p])] - len[lca(x, id[q])] + len[lca(id[p], id[q])];
	}
}
void append (int x) {
	ans += calc(x);
	s.insert(dfn[x]);
}
void remove (int x) {
	s.erase(dfn[x]);
	ans -= calc(x);
}
int main () {
	scanf("%d", &n);
	for (int i = 1, x, y, z; i < n; ++i) {
		scanf("%d%d%d", &x, &y, &z);
		add(x, y, z), add(y, x, z);
	}
	dfs(1, 0);
	scanf("%d", &q);
	for (int i = 1; i <= q; ++i) {
		char op[5]; int x;
		scanf("%s%d", op, &x);
		if (op[0] == '+') {
			append(x);
		} else {
			remove(x);
		}
		printf("%lld
", ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/psimonw/p/11803074.html