Description
有一棵点数为 N 的树,以点 1 为根,且树点有边权。然后有 M 个
操作,分为三种:
操作 1 :把某个节点 x 的点权增加 a 。
操作 2 :把某个节点 x 为根的子树中所有点的点权都增加 a 。
操作 3 :询问某个节点 x 到根的路径中所有点的点权和。
Input
第一行包含两个整数 N, M 。表示点数和操作数。接下来一行 N 个整数,表示树中节点的初始权值。接下来 N-1
行每行三个正整数 fr, to , 表示该树中存在一条边 (fr, to) 。再接下来 M 行,每行分别表示一次操作。其中
第一个数表示该操作的种类( 1-3 ) ,之后接这个操作的参数( x 或者 x a ) 。
Output
对于每个询问操作,输出该询问的答案。答案之间用换行隔开。
Sample Input
5 5
1 2 3 4 5
1 2
1 4
2 3
2 5
3 3
1 2 1
3 5
2 1 2
3 3
1 2 3 4 5
1 2
1 4
2 3
2 5
3 3
1 2 1
3 5
2 1 2
3 3
Sample Output
69
13
题解
又是一道裸的树链剖分。
这里有一个新的操作,子树加。我们发现子树是一段连续的区间,所以在dfs2是标记一下右端点就行了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=200010;
int pre[maxn],last[maxn],other[maxn],num,dfs[maxn],top[maxn],dep[maxn];
int R[maxn],sz[maxn],fa[maxn],son[maxn],n,m,belong[maxn];
int cnt;
ll w[maxn];
struct tree{
int l,r;
ll sum,lazy;
}t[maxn*4];
void add(int x,int y){
num++;
pre[num]=last[x];
last[x]=num;
other[num]=y;
}
void dfs1(int x){
sz[x]=1;
for(int i=last[x];i;i=pre[i]){
int v=other[i];
if(v!=fa[x]){
dep[v]=dep[x]+1;
fa[v]=x;
dfs1(v);
sz[x]+=sz[v];
if(!son[x]||sz[son[x]]<sz[v])
son[x]=v;
}
}
}
void dfs2(int x,int tp){
dfs[x]=++cnt;//他没儿子也要标号
belong[cnt]=x;
top[x]=tp;
if(son[x]) dfs2(son[x],tp);
for(int i=last[x];i;i=pre[i]){
int v=other[i];
if(v==fa[x]||v==son[x])
continue;
dfs2(v,v);
}
R[x]=cnt;
}
void build(int x,int l,int r){
t[x].l=l;t[x].r=r;
if(l==r){
t[x].sum=w[belong[l]];
return ;
}
int mid=(l+r)>>1;
build(x*2,l,mid);
build(x*2+1,mid+1,r);
t[x].sum=t[x*2].sum+t[x*2+1].sum;
}
void update(int x){
if(t[x].l==t[x].r){
t[x].lazy=0;
return ;
}
t[x*2].sum+=(ll)(t[x*2].r-t[x*2].l+1)*t[x].lazy;
t[x*2].lazy+=t[x].lazy;
t[x*2+1].sum+=(ll)(t[x*2+1].r-t[x*2+1].l+1)*t[x].lazy;
t[x*2+1].lazy+=t[x].lazy;
t[x].lazy=0;
}
void change(int x,int l,int r,long long k){
if(t[x].l>r||t[x].r<l)
return ;
if(t[x].l>=l&&t[x].r<=r){
t[x].sum+=(t[x].r-t[x].l+1)*k;
t[x].lazy+=k;
return ;
}
if(t[x].lazy)
update(x);
change(x*2,l,r,k);
change(x*2+1,l,r,k);
t[x].sum=t[x*2].sum+t[x*2+1].sum;
}
ll query(int x,int l,int r){
if(t[x].l>r||t[x].r<l){
return 0;
}
if(t[x].l>=l&&t[x].r<=r){
return t[x].sum;
}
if(t[x].lazy)
update(x);
return query(x*2,l,r)+query(x*2+1,l,r);
}
ll work(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+=query(1,dfs[f1],dfs[l]);
l=fa[f1];f1=top[l];
}
if (dep[l]>dep[r]) swap(l,r);
ans+=query(1,dfs[l],dfs[r]);
return ans;
}
int main(){
int x,type;long long y;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%lld",&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);
for(int i=1;i<=m;i++){
scanf("%d",&type);
if(type==3){
scanf("%d",&x);
printf("%lld\n",work(x,1));
}
else if(type==2){
scanf("%d%lld",&x,&y);
change(1,dfs[x],R[x],y);
}
else{
scanf("%d%lld",&x,&y);
change(1,dfs[x],dfs[x],y);
}
}
return 0;
}