题意:一棵树,有n个点,每个点都有一个权值,有两种操作,0 a b ,问从节点a到节点b路径上所有点权值和,1 a b,把节点a权值改为b。
题解:树链剖分水题。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30005;
struct Edge {
int u, v, nxt;
Edge() {};
Edge(int a, int b, int c): u(a), v(b), nxt(c) {}
}e[N << 1];
int val[N], size[N], dep[N], son[N], fa[N], top[N];
int n, q, cnt, tot, head[N], tree[N << 2], id[N];
void AddEdge(int u, int v) {
e[cnt] = Edge(u, v, head[u]);
head[u] = cnt++;
e[cnt] = Edge(v, u, head[v]);
head[v] = cnt++;
}
void dfs2(int u, int tp) {
top[u] = tp;
id[u] = ++tot;
if (son[u]) dfs2(son[u], tp);
for (int i = head[u]; i + 1; i = e[i].nxt) {
int v = e[i].v;
if (v == fa[u] || v == son[u]) continue;
dfs2(v, v);
}
}
void dfs1(int u, int f, int depth) {
size[u] = 1, dep[u] = depth, son[u] = 0, fa[u] = f;
for (int i = head[u]; i + 1; i = e[i].nxt) {
int v = e[i].v;
if (v == f) continue;
dfs1(v, u, depth + 1);
size[u] += size[v];
if (size[v] > size[son[u]]) son[u] = v;
}
}
void pushup(int k) {
tree[k] = tree[k * 2] + tree[k * 2 + 1];
}
void modify(int k, int left, int right, int pos, int v) {
if (left == right) {
tree[k] = v;
return;
}
int mid = (left + right) / 2;
if (pos <= mid)
modify(k * 2, left, mid, pos, v);
else
modify(k * 2 + 1, mid + 1, right, pos, v);
pushup(k);
}
int query(int k, int left, int right, int l, int r) {
if (l <= left && right <= r)
return tree[k];
int mid = (left + right) / 2, res = 0;
if (l <= mid)
res += query(k * 2, left, mid, l, r);
if (r > mid)
res += query(k * 2 + 1, mid + 1, right, l, r);
return res;
}
void init() {
memset(head, -1, sizeof(head));
cnt = tot = 0;
int u, v;
for (int i = 0; i < n - 1; i++) {
scanf("%d%d", &u, &v);
AddEdge(u + 1, v + 1);
}
dfs1(1, 0, 1);
dfs2(1, 1);
memset(tree, 0, sizeof(tree));
for (int i = 1; i <= n; i++)
modify(1, 1, tot, id[i], val[i]);
}
void solve(int u, int v) {
int tp1 = top[u], tp2 = top[v];
int res = 0;
while (tp1 != tp2) {
if (dep[tp1] < dep[tp2]) {
swap(tp1, tp2);
swap(u, v);
}
res += query(1, 1, tot, id[tp1], id[u]);
u = fa[tp1];
tp1 = top[u];
}
if (dep[u] > dep[v]) swap(u, v);
res += query(1, 1, tot, id[u], id[v]);
printf("%d\n", res);
}
int main() {
int t, cas = 1;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &val[i]);
init();
scanf("%d", &q);
int op, a, b;
printf("Case %d:\n", cas++);
while (q--) {
scanf("%d%d%d", &op, &a, &b);
if (op == 1)
modify(1, 1, tot, id[a + 1], b);
else
solve(a + 1, b + 1);
}
}
return 0;
}