# BZOJ 4034 树上操作

## 做法 : 欧拉序列 + 线段树

#include<bits/stdc++.h>
#include<vector>
using namespace std;

const int maxn = 200000 + 55;
const int N = maxn * 6;

int n, m, cnt = 0;
int a[maxn], b[N], dfn[maxn], low[maxn]; bool io[N];
vector<int> G[maxn];

inline void dfs(int x, int fat) {
++ cnt; b[cnt] = a[x]; dfn[x] = cnt; io[cnt] = 1;
for (int i = 0; i < G[x].size(); ++ i) {
int v = G[x][i]; if (v == fat) continue;
dfs(v, x);
}
++ cnt; b[cnt] = -a[x]; low[x] = cnt; io[cnt] = 0;
}

const int maxm = 2400010;

int L[maxm + 1], R[maxm + 1];
long long lazy[maxm + 1], flag[maxm + 1];
long long w[maxm + 1];

inline void build(int pos, int l, int r) {
L[pos] = l; R[pos] = r; w[pos] = lazy[pos] = 0;
if (l == r) {
w[pos] = (long long) b[l];
if (io[l]) flag[pos] = 1;
else flag[pos] = -1;
return;
}
int mid = (l + r) >> 1;
build(pos << 1, l, mid);
build(pos << 1 | 1, mid + 1, r);
w[pos] = w[pos << 1] + w[pos << 1 | 1];
flag[pos] = flag[pos << 1] + flag[pos << 1 | 1];
}

inline void pushdown(int x) {
if (!lazy[x]) return;
w[x << 1] += lazy[x] * flag[x << 1];
w[x << 1 | 1] += lazy[x] * flag[x << 1 | 1];
lazy[x << 1] += lazy[x];
lazy[x << 1 | 1] += lazy[x];
lazy[x] = 0;
}

inline void update(int x, int l, int r, long long delta) {
if (l <= L[x] && R[x] <= r) {
w[x] = w[x] + flag[x] * delta;
lazy[x] += delta;
return;
}
pushdown(x);
int mid = (L[x] + R[x]) >> 1;
if (l > mid) update(x << 1 | 1, l, r, delta);
else if (r <= mid) update(x << 1, l, r, delta);
else {
update(x << 1, l, mid, delta);
update(x << 1 | 1, mid + 1, r, delta);
}
w[x] = w[x << 1] + w[x << 1 | 1];
}

inline long long query(int x, int l, int r) {
if (l <= L[x] && R[x] <= r) {
return w[x];
}
pushdown(x);
int mid = (L[x] + R[x]) >> 1;
if (l > mid) return query(x << 1 | 1, l, r);
else if (r <= mid) return query(x << 1, l, r);
else {
return query(x << 1, l, mid) + query(x << 1 | 1, mid + 1, r);
}
}

int main(void) {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++ i) scanf("%d", &a[i]);
for (int i = 1; i < n; ++ i) {
int x, y; scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs(1, 0);
build(1, 1, cnt);
while (m --) {
int op; scanf("%d", &op);
if (op == 1) {
int x, del; scanf("%d%d", &x, &del);
update(1, dfn[x], dfn[x], (long long)del);
update(1, low[x], low[x], (long long)del);
} else if (op == 2) {
int x, del; scanf("%d%d", &x, &del);
update(1, dfn[x], low[x], (long long)del);
} else if (op == 3) {
int x; scanf("%d", &x);
printf("%lld\n", query(1, 1, dfn[x]));
}
}
return 0;
}


posted @ 2018-07-14 11:49  Iamhx  阅读(116)  评论(0编辑  收藏  举报