题意
询问树上路径最大值,和,单点修改。
思路
树链剖分水题,简单线段树维护一下。
代码
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
struct segmentTree {
int ls, rs, l, r, datMax, datSum;
}t[60001];
int a[30001];
int head[30001], ver[60001], next[60001];
int father[30001], dep[30001], size[30001], son[30001], rev[30001], top[30001], seg[30001];
int n, m, tot, cnt;
void add(int u, int v) {
ver[++tot] = v;
next[tot] = head[u];
head[u] = tot;
}
void dfs1(int u, int fa) {
father[u] = fa;
size[u] = 1;
dep[u] = dep[fa] + 1;
for (int i = head[u]; i; i = next[i]) {
if (ver[i] == fa) continue;
dfs1(ver[i], u);
size[u] += size[ver[i]];
if (size[ver[i]] > size[son[u]] || !son[u]) son[u] = ver[i];
}
}
void dfs2(int u, int t) {
top[u] = t;
seg[u] = ++cnt;
rev[cnt] = u;
if (!son[u]) return;
dfs2(son[u], t);
for (int i = head[u]; i; i = next[i]) {
if (ver[i] == father[u] || son[u] == ver[i]) continue;
dfs2(ver[i], ver[i]);
}
}
void build(int p, int l, int r) {
t[p].l = l, t[p].r = r;
if (l == r) {
t[p].datSum = t[p].datMax = a[rev[l]];
return;
}
int mid = l + r >> 1;
build(t[p].ls = ++cnt, l, mid);
build(t[p].rs = ++cnt, mid + 1, r);
t[p].datSum = t[t[p].ls].datSum + t[t[p].rs].datSum;
t[p].datMax = std::max(t[t[p].ls].datMax, t[t[p].rs].datMax);
}
int query(int p, int l, int r, int op) {
if (l <= t[p].l && t[p].r <= r)
return op ? t[p].datSum : t[p].datMax;
int mid = t[p].l + t[p].r >> 1, res = op ? 0 : -30000;
if (l <= mid) op ? res += query(t[p].ls, l, r, op) : res = std::max(res, query(t[p].ls, l, r, op));
if (r > mid) op ? res += query(t[p].rs, l, r, op) : res = std::max(res, query(t[p].rs, l, r, op));
return res;
}
void update(int p, int pos, int val) {
if (t[p].l == t[p].r) {
t[p].datSum = t[p].datMax = val;
return;
}
int mid = t[p].l + t[p].r >> 1;
if (pos <= mid) update(t[p].ls, pos, val);
else update(t[p].rs, pos, val);
t[p].datSum = t[t[p].ls].datSum + t[t[p].rs].datSum;
t[p].datMax = std::max(t[t[p].ls].datMax, t[t[p].rs].datMax);
}
int ask(int x, int y, int op) {
int res = op ? 0 : -30000;
while (top[x] != top[y]) {
if (dep[top[x]] < dep[top[y]]) std::swap(x, y);
op ? res += query(1, seg[top[x]], seg[x], op) : res = std::max(res, query(1, seg[top[x]], seg[x], op));
x = father[top[x]];
}
if (dep[x] > dep[y]) std::swap(x, y);
op ? res += query(1, seg[x], seg[y], op) : res = std::max(res, query(1, seg[x], seg[y], op));
return res;
}
int main() {
scanf("%d", &n);
for (int i = 1, x, y; i < n; i++) {
scanf("%d %d", &x, &y);
add(x, y), add(y, x);
}
dfs1(1, 0);
dfs2(1, 1);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
build(cnt = 1, 1, n);
scanf("%d", &m);
std::string op;
for (int x, y; m; m--) {
std::cin >> op;
scanf("%d %d", &x, &y);
if (op == "CHANGE") update(1, seg[x], y);
else if (op == "QMAX") printf("%d\n", ask(x, y, 0));
else if (op == "QSUM") printf("%d\n", ask(x, y, 1));
}
}