【Luogu1501】Tree(Link-Cut Tree)
【Luogu1501】Tree(Link-Cut Tree)
题面
题解
\(LCT\)版子题
看到了顺手敲一下而已
注意一下,别乘爆了
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAX 120000
#define MOD 51061
#define lson (t[x].ch[0])
#define rson (t[x].ch[1])
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
struct Node
{
int ch[2],ff;
int rev,v,size;
int sum,lc,lp;
}t[MAX];
int S[MAX],top;
int n,Q;
bool isroot(int x){return t[t[x].ff].ch[0]!=x&&t[t[x].ff].ch[1]!=x;}
void pushup(int x)
{
t[x].sum=(t[lson].sum+t[rson].sum+t[x].v)%MOD;
t[x].size=(t[lson].size+t[rson].size+1)%MOD;
}
void rotate(int x)
{
int y=t[x].ff,z=t[y].ff;
int k=t[y].ch[1]==x;
if(!isroot(y))t[z].ch[t[z].ch[1]==y]=x;t[x].ff=z;
t[y].ch[k]=t[x].ch[k^1];t[t[x].ch[k^1]].ff=y;
t[x].ch[k^1]=y;t[y].ff=x;
pushup(y);pushup(x);
}
void putrev(int x){swap(lson,rson);t[x].rev^=1;}
void putmul(int x,int w)
{
t[x].lc=1ll*t[x].lc*w%MOD;t[x].lp=1ll*t[x].lp*w%MOD;
t[x].v=1ll*t[x].v*w%MOD;t[x].sum=1ll*t[x].sum*w%MOD;
}
void putplu(int x,int w)
{
(t[x].lp+=w)%=MOD;
(t[x].v+=w)%=MOD;
(t[x].sum+=1ll*w*t[x].size%MOD)%=MOD;
}
void pushdown(int x)
{
if(t[x].rev)
{
if(lson)putrev(lson);if(rson)putrev(rson);
t[x].rev=0;
}
if(t[x].lc!=1)
{
if(lson)putmul(lson,t[x].lc);if(rson)putmul(rson,t[x].lc);
t[x].lc=1;
}
if(t[x].lp)
{
if(lson)putplu(lson,t[x].lp);if(rson)putplu(rson,t[x].lp);
t[x].lp=0;
}
}
void Splay(int x)
{
S[top=1]=x;
for(int i=x;!isroot(i);i=t[i].ff)S[++top]=t[i].ff;
while(top)pushdown(S[top--]);
while(!isroot(x))
{
int y=t[x].ff,z=t[y].ff;
if(!isroot(y))
(t[y].ch[1]==x)^(t[z].ch[1]==y)?rotate(x):rotate(y);
rotate(x);
}
}
void access(int x){for(int y=0;x;y=x,x=t[x].ff)Splay(x),t[x].ch[1]=y,pushup(x);}
void makeroot(int x){access(x);Splay(x);putrev(x);}
void split(int x,int y){makeroot(x);access(y);Splay(y);}
void cut(int x,int y){split(x,y);t[y].ch[0]=t[x].ff=0;pushup(y);}
void link(int x,int y){makeroot(x);t[x].ff=y;}
int findroot(int x){access(x);Splay(x);while(lson)x=lson;return x;}
int main()
{
n=read();Q=read();
for(int i=1;i<=n;++i)t[i].v=t[i].lc=1;
for(int i=1;i<n;++i)link(read(),read());
char ch[3];
while(Q--)
{
scanf("%s",ch);
int u=read(),v=read();
if(ch[0]=='+'){split(u,v);putplu(v,read());}
if(ch[0]=='-'){cut(u,v),link(read(),read());}
if(ch[0]=='*'){split(u,v);putmul(v,read());}
if(ch[0]=='/'){split(u,v);printf("%d\n",t[v].sum);}
}
return 0;
}