[HAOI2015]树上操作 T19 D71
作者:互联网
[HAOI2015]树上操作 T19 D71
树剖模板题
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define si size()
#define ls (p<<1)
#define rs ((p<<1)|1)
#define mid (t[p].l+t[p].r)/2
using namespace std;
ll read(){ll x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;}
inline void Prin(ll x){if(x < 0){putchar('-');x = -x;}if(x > 9) Prin(x / 10);putchar(x % 10 + '0');}
const int qs=1e5+7;
ll mod=1e16;
int n,m;
ll a[qs];
pii id[qs];
int son[qs],sz[qs],fr[qs],f[qs],cnt,dep[qs],top[qs];
vector<int> v[qs];
struct Tree{
ll val,add;
int l,r;
#define l(x) t[x].l
#define r(x) t[x].r
#define val(x) t[x].val
#define add(x) t[x].add
}t[qs<<2];
void pushup(int p){ val(p)=(val(ls)+val(rs))%mod;}
void down(int p){
if(!add(p)) return;
val(ls)=(val(ls)+add(p)*(r(ls)-l(ls)+1))%mod;
val(rs)=(val(rs)+add(p)*(r(rs)-l(rs)+1))%mod;
add(ls)=(add(ls)+add(p))%mod;
add(rs)=(add(rs)+add(p))%mod;
add(p)=0;
}
void build(int p,int l,int r){
l(p)=l,r(p)=r;add(p)=0;
if(l==r){
val(p)=a[fr[l]]%mod;
return;
}
build(ls,l,mid);
build(rs,mid+1,r);
pushup(p);
// cout<<"l="<<l<<" r="<<r<<" val="<<val(p)<<"\n";
}
void update(int p,int l,int r,ll val){
if(l<=l(p)&&r>=r(p)){
val(p)=(val(p)+val*(r(p)-l(p)+1))%mod;
add(p)=(add(p)+val)%mod;
//cout<<"l="<<l(p)<<" r="<<r(p)<<" val="<<val(p)<<"\n";
return;
}
down(p);
if(l<=mid) update(ls,l,r,val);
if(r>mid) update(rs,l,r,val);
pushup(p);
}
ll ask(int p,int l,int r){
if(l<=l(p)&&r>=r(p)) return val(p);
down(p);
ll val=0;
if(l<=mid) val=(val+ask(ls,l,r))%mod;
if(r>mid) val=(val+ask(rs,l,r))%mod;
return val;
}
void dfs(int x,int fa){
f[x]=fa; son[x]=0; sz[x]=1; dep[x]=dep[fa]+1;
int ms=0;
for(int i=0;i<v[x].si;++i){
int p=v[x][i];
if(p==fa) continue;
dfs(p,x);
if(sz[p]>ms) ms=sz[p],son[x]=p;
}
}
void dfn(int x,int po){
id[x].fi=++cnt; fr[cnt]=x;
top[x]=po;
if(!son[x]){
id[x].se=cnt;
return;
}
dfn(son[x],po);
for(int i=0;i<v[x].si;++i){
int p=v[x][i];
if(p==f[x]||p==son[x]) continue;
dfn(p,p);
}
id[x].se=cnt;
}
ll qRange(int x,int y){
ll ans=0,res=0;
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]]) swap(x,y);
res=ask(1,id[top[x]].fi,id[x].fi);
ans=ans+res;
x=f[top[x]];
}
if(dep[x]>dep[y]) swap(x,y);
res=ask(1,id[x].fi,id[y].fi);
ans=ans+res;
return ans;
}
int main(){
n=read(),m=read();
for(int i=1;i<=n;++i) a[i]=read();
int x,y,op,z;
for(int i=1;i<n;++i){
x=read(),y=read();
v[x].pb(y),v[y].pb(x);
}
dfs(1,0);
dfn(1,1);
build(1,1,n);
while(m--){
op=read(),x=read();
if(op==1){
z=read();
update(1,id[x].fi,id[x].fi,z);
}
else if(op==2){
z=read();
update(1,id[x].fi,id[x].se,z);
}
else{
cout<<qRange(1,x)<<"\n";
}
}
}
标签:qs,D71,val,int,ll,son,HAOI2015,T19,define 来源: https://www.cnblogs.com/Suki-Sugar/p/15435007.html