BZOJ 1036 树的统计 | 树链剖分模板题
又做了一遍……去掉读入优化只有八十行~
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
#define space putchar(' ')
#define enter putchar('\n')
template <class T>
void read(T &x){
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-') op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op) x = -x;
}
template <class T>
void write(T x){
if(x < 0) putchar('-'), x = -x;
if(x >= 10) write(x / 10);
putchar('0' + x % 10);
}
const int N = 30005;
int n, m;
int ecnt, adj[N], go[2*N], nxt[2*N];
int tot, dep[N], fa[N], son[N], top[N], sze[N], val[N], pos[N], idx[N];
int sum[4*N], mx[4*N];
void add(int u, int v){
go[++ecnt] = v;
nxt[ecnt] = adj[u];
adj[u] = ecnt;
}
void pushup(int k){
sum[k] = sum[k << 1] + sum[k << 1 | 1];
mx[k] = max(mx[k << 1], mx[k << 1 | 1]);
}
void build(int k, int l, int r){
if(l == r) return (void)(sum[k] = mx[k] = val[idx[l]]);
int mid = (l + r) >> 1;
build(k << 1, l, mid);
build(k << 1 | 1, mid + 1, r);
pushup(k);
}
void change(int k, int l, int r, int p, int x){
if(l == r) return (void)(sum[k] = mx[k] = x);
int mid = (l + r) >> 1;
if(p <= mid) change(k << 1, l, mid, p, x);
else change(k << 1 | 1, mid + 1, r, p, x);
pushup(k);
}
int query(int k, int l, int r, int ql, int qr, bool is_sum){
if(ql <= l && qr >= r) return is_sum ? sum[k] : mx[k];
int mid = (l + r) >> 1;
if(qr <= mid) return query(k << 1, l, mid, ql, qr, is_sum);
if(ql > mid) return query(k << 1 | 1, mid + 1, r, ql, qr, is_sum);
if(is_sum) return query(k << 1, l, mid, ql, qr, 1) + query(k << 1 | 1, mid + 1, r, ql, qr, 1);
else return max(query(k << 1, l, mid, ql, qr, 0), query(k << 1 | 1, mid + 1, r, ql, qr, 0));
}
int path_query(int u, int v, bool is_sum){
if(top[u] == top[v]){
if(pos[u] > pos[v]) swap(u, v);
return query(1, 1, n, pos[u], pos[v], is_sum);
}
if(dep[top[u]] > dep[top[v]]) swap(u, v);
if(is_sum) return query(1, 1, n, pos[top[v]], pos[v], 1) + path_query(fa[top[v]], u, 1);
else return max(query(1, 1, n, pos[top[v]], pos[v], 0), path_query(fa[top[v]], u, 0));
}
void init(){
static int que[N], qr;
que[qr = 1] = 1;
for(int ql = 1, u; ql <= qr; ql++){
u = que[ql], dep[u] = dep[fa[u]] + 1, sze[u] = 1;
for(int e = adj[u], v; e; e = nxt[e])
if(v = go[e], v != fa[u])
fa[v] = u, que[++qr] = v;
}
for(int ql = qr, u; ql; ql--){
u = que[ql];
sze[fa[u]] += sze[u];
if(sze[u] >= sze[son[fa[u]]]) son[fa[u]] = u;
}
for(int ql = 1, u; ql <= qr; ql++)
if(!top[u = que[ql]])
for(int v = u; v; v = son[v])
top[v] = u, pos[v] = ++tot, idx[tot] = v;
build(1, 1, n);
}
int main(){
read(n);
for(int i = 1, u, v; i < n; i++)
read(u), read(v), add(u, v), add(v, u);
for(int i = 1; i <= n; i++)
read(val[i]);
init();
read(m);
int u, v;
char op[10];
while(m--){
scanf("%s", op);
read(u), read(v);
if(op[0] == 'C') change(1, 1, n, pos[u], v);
else write(path_query(u, v, op[1] == 'S')), enter;
}
return 0;
}
本文作者:胡小兔
博客地址:http://rabbithu.cnblogs.com
博客地址:http://rabbithu.cnblogs.com