传送门
写在前面:大晚上写题解,明天上午去看电影,可以的~~
思路:比较裸的树链剖分,比起普通的链剖,这里加了一步对子树(包括自己)的权值修改,这其实很简单,因为我们dfs时任一个子树的区间[L,R]在线段树上都是连续的,而且显然L记录该子树根的权值,R记录子树最右边的点的权值,可以对整棵子树dfs后得到,接下来就是打上lazy标记的线段树操作了
注意:
计算答案一定要开longlong,而且有些中间步骤如果是用int计算一定要加“强制类型转换”
代码:
#include"bits/stdc++.h"
#define LL long long
using namespace std;
int n,m,opr,x,y,tot,cnt;
int pre[100010],w[100010],top[100010],fa[100010],son[100010],first[100010],dep[100010],siz[100010],L[100010],R[100010];
struct os
{
int u,v,next;
}e[200010];
struct node
{
LL sum,lazy;
}tree[800010];
void pushdown(int now,int begin,int end)
{
int mid=(begin+end)>>1;
tree[now<<1].sum+=(mid-begin+1)*tree[now].lazy;
tree[now<<1].lazy+=tree[now].lazy;
tree[now<<1|1].sum+=(end-mid)*tree[now].lazy;
tree[now<<1|1].lazy+=tree[now].lazy;
tree[now].lazy=0;
}
void add(int x,int y)
{
e[++tot].u=x;
e[tot].v=y;
e[tot].next=first[x];
first[x]=tot;
}
void dfs1(int now)
{
siz[now]=1;
for (int i=first[now];i;i=e[i].next)
if (e[i].v!=fa[now])
{
dep[e[i].v]=dep[now]+1;
fa[e[i].v]=now;
dfs1(e[i].v);
if (siz[e[i].v]>siz[son[now]]) son[now]=e[i].v;
siz[now]+=siz[e[i].v];
}
}
void dfs2(int now,int tp)
{
L[now]=++cnt;
pre[cnt]=now;
top[now]=tp;
if (son[now]) dfs2(son[now],tp);
for (int i=first[now];i;i=e[i].next)
if (e[i].v!=fa[now]&&e[i].v!=son[now])
dfs2(e[i].v,e[i].v);
R[now]=cnt;
}
void build(int now,int begin,int end)
{
if (begin==end) {tree[now].sum=w[pre[end]];return;}
int mid=(begin+end)>>1;
build(now<<1,begin,mid);
build(now<<1|1,mid+1,end);
tree[now].sum=tree[now<<1].sum+tree[now<<1|1].sum;
}
void update(int now,int begin,int end,int l,int r,int num)
{
if (l<=begin&&end<=r) {tree[now].lazy+=num;tree[now].sum+=(LL)num*(LL)(end-begin+1);return;}
pushdown(now,begin,end);
int mid=(begin+end)>>1;
if (mid>=l) update(now<<1,begin,mid,l,r,num);
if (mid<r) update(now<<1|1,mid+1,end,l,r,num);
tree[now].sum=tree[now<<1].sum+tree[now<<1|1].sum;
}
LL get_sum(int now,int begin,int end,int l,int r)
{
if (l<=begin&&end<=r) return tree[now].sum;
pushdown(now,begin,end);
int mid=(begin+end)>>1;
LL ans=0;
if (mid>=l) ans+=get_sum(now<<1,begin,mid,l,r);
if (mid<r) ans+=get_sum(now<<1|1,mid+1,end,l,r);
return ans;
}
LL solve(int l,int r)
{
int f1=top[l],f2=top[r];
LL ans=0;
while (f1!=f2)
{
if (dep[f1]<dep[f2]) swap(f1,f2),swap(l,r);
ans+=get_sum(1,1,cnt,L[f1],L[l]);
l=fa[f1];f1=top[l];
}
if (dep[l]>dep[r]) swap(l,r);
ans+=get_sum(1,1,cnt,L[l],L[r]);
return ans;
}
main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&w[i]);
for (int i=1;i<n;i++)
scanf("%d%d",&x,&y),
add(x,y),
add(y,x);
dfs1(1);
dfs2(1,1);
build(1,1,cnt);
while (m--)
{
scanf("%d",&opr);
if (opr==3)
{
scanf("%d",&x);
printf("%lld\n",solve(x,1));
}
else
{
scanf("%d%d",&x,&y);
if (opr==1)
update(1,1,cnt,L[x],L[x],y);
else update(1,1,cnt,L[x],R[x],y);
}
}
}