树链剖分模板题目。
树链剖分,就是先选定好根节点,由根节点往下,沿着子树节点最多的节点往下,将其拆成链,再由链组成线段树的数据结构
#pragma comment(linker,"/STACK:100000000,100000000")
#include
#include
#include
#include
using namespace std;
const int MAXN = 50010;
struct Edge{
int to, next;
};
int n, m, Q;
Edge edge[2*MAXN];
int head[MAXN], tot;
int top[MAXN];//每个节点所在链的头节点的位置
int fa[MAXN];//每个节点的父亲节点
int deep[MAXN];//每个节点的深度
int num[MAXN];//以第i个节点为根节点时子节点的个数
int p[MAXN];//i节点在线段树的位置
int fp[MAXN];//p的反函数
int son[MAXN];//每个节点的最大分支的儿子节点
int a[MAXN];
int pos;
void init()
{
tot = 0;
memset(head, -1, sizeof(head));
pos = 1;
memset(son, -1, sizeof(son));
}
void addedge(int u, int v)
{
edge[tot].to = v; edge[tot].next = head[u];
head[u] = tot++;
}
void dfs1(int u, int father ,int dep)
{
deep[u] = dep;
fa[u] = father;
num[u] = 1;
for (int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if (v != father) {
dfs1(v, u, dep+1);
num[u] += num[v];
if (son[u] == -1 || num[v] > num[son[u]])
son[u] = v;
}
}
}
void getpos(int u, int sp)
{
top[u] = sp;
p[u] = pos++;
fp[p[u]] = u;
if (son[u] == -1) return;
getpos(son[u], sp);
for (int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if (v != fa[u] && v != son[u]) {
getpos(v, v);
}
}
}
#define lson o<<1,l,mid
#define rson o<<1|1,mid+1,r
int sum[MAXN<<2];
void build(int o, int l, int r) {
if (l == r) { sum[o] = a[fp[l]]; return; }
int mid = (l+r) >> 1;
build(lson); build(rson);
sum[o] = 0;
}
void pushdown(int o) {
if (sum[o]) {
sum[o<<1] += sum[o];
sum[o<<1|1] += sum[o];
sum[o] = 0;
}
}
int query(int o, int l, int r, int v) {
if (l == r) return sum[o];
pushdown(o);
int mid = (l+r) >> 1;
if (v <= mid) return query(lson, v);
return query(rson, v);
}
void update(int o, int l, int r, int L, int R, int v) {
if (l >= L && r <= R) { sum[o] += v; return ; }
pushdown(o);
int mid = (l+r) >> 1;
if (L <= mid) update(lson, L, R, v);
if (R > mid) update(rson, L, R, v);
}
void change(int x, int y, int w, int n) {
while (top[x] != top[y]) {
if (deep[top[x]] < deep[top[y]]) swap(x, y);
update(1, 1, n, p[top[x]], p[x], w);
x = fa[top[x]];
}
if (deep[x] > deep[y]) swap(x, y);
update(1, 1, n, p[x], p[y], w);
}
char buf[5];
int x, y, z;
int main()
{
while (scanf("%d%d%d" , &n, &m, &Q) != EOF) {
for (int i = 1; i <= n; i++)
scanf("%d", a+i);
init();
for (int i = 1; i <= m; i++) {
scanf("%d%d", &x, &y);
addedge(x, y);
addedge(y, x);
}
dfs1(1, 0, 0);
getpos(1, 1);
build(1, 1, n);
for (int i = 1; i <= Q; i++) {
scanf("%s", buf);
if (buf[0] == 'Q') {
scanf("%d", &x);
printf("%d\n", query(1, 1, n, p[x]));
}
else {
scanf("%d%d%d", &x, &y, &z);
if (buf[0] == 'D') z = -z;
change(x, y, z, n);
}
}
}
return 0;
}