#include<cstdio>
#include<algorithm>
#define ll long long
#define N 200010
using namespace std;
struct node{int v,fr;}e[N<<2];
int n,m,r,p,a[N],tail[N],cnt=0,tot=0;
int siz[N],fa[N],son[N],zf[N],dep[N];
int dfn[N],t[N<<4],lazy[N<<4],tt,x,y,z;
inline int read()
{
int x=0; char c=getchar();
while (c<'0' || c>'9') c=getchar();
while (c>='0' && c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x;
}
void add(int u,int v) {e[++cnt]=(node){v,tail[u]}; tail[u]=cnt;}
void dfs1(int x)
{
siz[x]=1;
for (int p=tail[x],v;p;p=e[p].fr)
if ((v=e[p].v)!=fa[x])
{
dep[v]=dep[x]+1,fa[v]=x,dfs1(v),siz[x]+=siz[v];
if (siz[son[x]]<siz[v]) son[x]=v;
}
}
void ad(int x,int l,int r,int f,int in)
{
if (l==r) {t[x]=in; return;}
int mid=l+r>>1;
if (f<=mid) ad(x<<1,l,mid,f,in);
else ad(x<<1|1,mid+1,r,f,in);
t[x]=t[x<<1]+t[x<<1|1];
}
void dfs2(int x,int gf)
{
dfn[x]=++tot,ad(1,1,n,tot,a[x]),zf[x]=gf;
if (!son[x]) return;
dfs2(son[x],gf);
for (int p=tail[x],v;p;p=e[p].fr)
if ((v=e[p].v)!=fa[x] && v!=son[x]) dfs2(v,v);
}
void update(int x,int l,int r)
{
if (!lazy[x]) return;
t[x]=(t[x]+(ll)(r-l+1)*lazy[x]%p)%p;
if (l<r) lazy[x<<1]=(lazy[x<<1]+lazy[x])%p,lazy[x<<1|1]=(lazy[x<<1|1]+lazy[x])%p;
lazy[x]=0;
}
void insert(int x,int l,int r,int fl,int fr,int ins)
{
if (fl==l && fr==r)
{
lazy[x]=(lazy[x]+ins)%p;
update(x,l,r);
return;
}
update(x,l,r);
int mid=l+r>>1;
if (fr<=mid) insert(x<<1,l,mid,fl,fr,ins);
else if (fl>mid) insert(x<<1|1,mid+1,r,fl,fr,ins);
else insert(x<<1,l,mid,fl,mid,ins),insert(x<<1|1,mid+1,r,mid+1,fr,ins);
update(x<<1,l,mid),update(x<<1|1,mid+1,r);
t[x]=(t[x<<1]+t[x<<1|1])%p;
}
void change(int x,int y,int z)
{
z%=p;
while (zf[x]!=zf[y])
{
if (dep[zf[x]]<dep[zf[y]]) swap(x,y);
insert(1,1,n,dfn[zf[x]],dfn[x],z);
x=fa[zf[x]];
}
if (dep[x]>dep[y]) swap(x,y);
insert(1,1,n,dfn[x],dfn[y],z);
}
int query(int x,int l,int r,int fl,int fr)
{
update(x,l,r);
if (l==fl && r==fr) return t[x];
int mid=l+r>>1;
if (fr<=mid) return query(x<<1,l,mid,fl,fr);
else if (fl>mid) return query(x<<1|1,mid+1,r,fl,fr);
else return (query(x<<1,l,mid,fl,mid)+query(x<<1|1,mid+1,r,mid+1,fr))%p;
}
int gans(int x,int y)
{
int s=0;
while (zf[x]!=zf[y])
{
if (dep[zf[x]]<dep[zf[y]]) swap(x,y);
s=(s+query(1,1,n,dfn[zf[x]],dfn[x]))%p;
x=fa[zf[x]];
}
if (dep[x]>dep[y]) swap(x,y);
return (s+query(1,1,n,dfn[x],dfn[y]))%p;
}
int main()
{
freopen("P3384.in","r",stdin);
freopen("P3384.out","w",stdout);
n=read(),m=read(),r=read(),p=read();
for (int i=1;i<=n;i++) a[i]=read();
for (int i=1,u,v;i<n;i++)
u=read(),v=read(),add(u,v),add(v,u);
dfs1(r),dfs2(r,r);
while (m--)
{
tt=read();
if (tt==1) x=read(),y=read(),z=read(),change(x,y,z);
else if (tt==2) x=read(),y=read(),printf("%d\n",gans(x,y));
else if (tt==3) x=read(),y=read(),insert(1,1,n,dfn[x],dfn[x]+siz[x]-1,y);
else x=read(),printf("%d\n",query(1,1,n,dfn[x],dfn[x]+siz[x]-1));
}
return 0;
}
洛谷 P3384 【模板】树链剖分
最新推荐文章于 2022-07-04 03:39:00 发布