题意:有一棵树,有n个点,n - 1条边,给出每个节点的权值,有三种操作,qmax a b询问a到b所有点的最大权值,qsum a b询问a到b所有点权值和,change a b把节点a权值设为b。
题解:两颗线段树,维护最大值和区间和。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30005;
const int INF = 0x3f3f3f3f;
struct Edge {
int u, v, nxt;
Edge() {}
Edge(int a, int b, int c): u(a), v(b), nxt(c) {}
}e[N << 1];
int size[N], top[N], son[N], fa[N], dep[N], id[N];
int n, q, cnt, tot, head[N], val[N], tree[N << 2], sum[N << 2];
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, son[u] = 0, fa[u] = f, dep[u] = depth + 1;
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[son[u]] < size[v]) son[u] = v;
}
}
void pushup(int k) {
tree[k] = max(tree[k * 2], tree[k * 2 + 1]);
sum[k] = sum[k * 2] + sum[k * 2 + 1];
}
void modify(int k, int left, int right, int pos, int v) {
if (left == right) {
tree[k] = sum[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, int flag) {
if (l <= left && right <= r) {
if (!flag) return tree[k];
return sum[k];
}
int mid = (left + right) / 2, res;
if (!flag) res = -INF;
else res = 0;
if (l <= mid) {
if (!flag) res = max(res, query(k * 2, left, mid, l, r, flag));
else res += query(k * 2, left, mid, l, r, flag);
}
if (r > mid) {
if (!flag) res = max(res, query(k * 2 + 1, mid + 1, right, l, r, flag));
else res += query(k * 2 + 1, mid + 1, right, l, r, flag);
}
return res;
}
void solve(int u, int v, int flag) {
int tp1 = top[u], tp2 = top[v], res;
if (!flag) res = -INF;
else res = 0;
while (tp1 != tp2) {
if (dep[tp1] < dep[tp2]) {
swap(tp1, tp2);
swap(u, v);
}
if (!flag) res = max(res, query(1, 1, tot, id[tp1], id[u], 0));
else res += query(1, 1, tot, id[tp1], id[u], 1);
u = fa[tp1];
tp1 = top[u];
}
if (dep[u] > dep[v]) swap(u, v);
if (!flag) res = max(res, query(1, 1, tot, id[u], id[v], 0));
else res += query(1, 1, tot, id[u], id[v], 1);
printf("%d\n", res);
}
int main() {
while (scanf("%d", &n) == 1) {
int u, v;
cnt = tot = 0;
memset(head, -1, sizeof(head));
memset(tree, 0, sizeof(tree));
memset(sum, 0, sizeof(sum));
for (int i = 1; i < n; i++) {
scanf("%d%d", &u, &v);
AddEdge(u, v);
}
for (int i = 1; i <= n; i++)
scanf("%d", &val[i]);
dfs1(1, 0, 1);
dfs2(1, 1);
for (int i = 1; i <= n; i++)
modify(1, 1, tot, id[i], val[i]);
scanf("%d", &q);
char op[10];
int a, b;
while (q--) {
scanf("%s%d%d", op, &a, &b);
if (op[1] == 'M')
solve(a, b, 0);
else if (op[1] == 'S')
solve(a, b, 1);
else
modify(1, 1, tot, id[a], b);
}
}
return 0;
}