思路:
考虑维护深度,那么子树加的时候相当于加一个与深度相关的等差数列,所以我们每个节点记录一个二元组
(a,b)
,表示
a×dep+b
,这样每次修改的系数就是相同的
a,b
了。
总的时间复杂度是:
O(qlogn)
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 100010;
typedef long long ll;
struct node{
ll a, b, tga, tgb;
node(){a = b = tga = tgb = 0;}
void update(ll A, ll B);
void down();
}T[maxn * 3];
int n, m;
int head[maxn], to[maxn<<1], nxt[maxn<<1], cnt;
int st[maxn], tp, pos[maxn], tim, num[maxn];
int sz[maxn], V[maxn];
ll v[maxn], dep[maxn];
void add(int a, int b){nxt[++ cnt] = head[a], to[head[a] = cnt] = b;}
#define mid ((l+r)>>1)
#define lch ((now<<1))
#define rch ((now<<1)|1)
void node::update(ll A, ll B){a += A, b += B, tga += A, tgb += B;}
void node::down(){
int now = (this - T);
T[lch].update(tga, tgb);
T[rch].update(tga, tgb);
tga = tgb = 0;
}
void build(int now, int l, int r){
if(l == r){
T[now].update(0, v[num[l]]);
return;
}
build(lch, l, mid);
build(rch, mid+1, r);
}
void dfs(int x, int fa){
sz[x] = 1, pos[x] = ++ tim, num[tim] = x;
for(int i = head[x]; i; i = nxt[i]){
int u = to[i]; if(u == fa) continue;
dep[u] = dep[x] + 1, v[u] = v[x] + V[u];
dfs(u, x), sz[x] += sz[u];
}
}
int gt(){
char c; int num = 0, op = 1; bool ok = 0;
while(1){
c = getchar();
if(c == '-') op = -1;
else if(c <= '9' && c >= '0') num = num * 10 + c - '0', ok = 1;
else if(ok) return num*op;
}
}
void modify(int now, int l, int r, int pos1, int pos2, ll a, ll b){
if(l == pos1 && r == pos2){T[now].update(a, b); return;} T[now].down();
if(pos2 <= mid) modify(lch, l, mid, pos1, pos2, a, b);
else if(pos1 >= mid+1) modify(rch, mid+1, r, pos1, pos2, a, b);
else modify(lch, l, mid, pos1, mid, a, b), modify(rch, mid+1, r, mid+1, pos2, a, b);
}
long long que(int now, int l, int r, int pos){
if(l == r) return 1LL * T[now].a * dep[num[l]] + T[now].b; T[now].down();
if(pos <= mid) return que(lch, l, mid, pos);
else return que(rch, mid+1, r, pos);
}
int main(){
n = gt(), m = gt();
for(int i = 1; i <= n; i ++) V[i] = gt();
for(int i = 1; i < n; i ++){
int a = gt(), b = gt();
add(a, b), add(b, a);
}
dep[1] = 1, v[1] = V[1], dfs(1, 0);
build(1, 1, n);
for(int i = 1; i <= m; i ++){
int op = gt(), x, a;
if(op == 1){
x = gt(), a = gt();
modify(1, 1, n, pos[x], pos[x] + sz[x] - 1, 0, a);
}else if(op == 2){
x = gt(), a = gt();
modify(1, 1, n, pos[x], pos[x] + sz[x] - 1, a, - 1LL * (dep[x] - 1) * a);
}else{
x = gt();
printf("%lld\n", que(1, 1, n, pos[x]));
}
}
return 0;
}