思路:
和线段树2 很像.
主要练习 LCT 的lazy标记.
我在写这个题的时候,没有看c 的取值可以是 0 ,结果就调了一上午,emmmm
if (mul[x] != 1 || add[x]){ //这个地方写错了. mul 有可能为 0 ,emmmmm.gg
一开开始写的是 mul[x] > 1
#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 100;
const int mod = 51061;
char s[20];
int f[N], rev[N], hep[N], ch[N][2],sz[N];
long long sum[N],val[N],mul[N],add[N];
inline int isroot(int x) {
return ch[f[x]][0] != x && ch[f[x]][1] != x;
}
inline void pushup(int x) {
sum[x] = sum[ch[x][0]] + sum[ch[x][1]] + val[x];
sum[x] %= mod;
sz[x] = sz[ch[x][0]] + sz[ch[x][1]] + 1;
}
inline void filp(int x) {
if (!x) return;
swap(ch[x][0], ch[x][1]);
rev[x] ^= 1; //标记表示已经翻转了该点的左右儿子
}
inline void change(int x, int y, int z){
val[x] = (val[x]*y + z) % mod;
sum[x] = (sum[x]*y + 1ll*z * sz[x]) % mod;
mul[x] = (mul[x] * y)%mod;
add[x] = (add[x] * y + z) % mod;
}
inline void pushdown(int x){
if (mul[x] != 1 || add[x]){ //这个地方写错了. mul 有可能为 0 ,emmmmm.gg
change(ch[x][0],mul[x],add[x]);
change(ch[x][1],mul[x],add[x]);
mul[x] = 1; add[x] = 0;
}
if (rev[x]) {
if (ch[x][0]) filp(ch[x][0]);
if (ch[x][1]) filp(ch[x][1]);
rev[x] = 0;
}
}
inline void rotate(int x){
int y = f[x], z = f[y], k = ch[y][1] == x, v = ch[x][!k];
if (!isroot(y)) ch[z][ch[z][1] == y] = x;//Attention if()
ch[x][!k] = y; ch[y][k] = v;
if (v) f[v] = y;
f[y] = x, f[x] = z;
pushup(y); pushup(x);
}
inline void splay(int x){
int y = x, top = 0; hep[++top] = y;
while(!isroot(y)) hep[++top] = y = f[y]; //这里个splay 不同之处,用一个栈存下来节点.
while(top) pushdown(hep[top--]); //然后一个一个的从上往下pushdown .
while(!isroot(x)){
y = f[x]; top = f[y];
if (!isroot(y))
rotate((ch[y][0] == y) ^ (ch[top][0] == y)?x:y);
rotate(x);
}
pushup(x);
}
inline void access(int x){
for(int y = 0; x; x = f[y = x])
splay(x), ch[x][1] = y, pushup(x);
}
inline void makeroot(int x){ //函数功能:把x拎成原图的根
access(x); splay(x); filp(x);
}
inline int findroot(int x){ //函数功能:找到x所在联通块的splay的根
access(x); splay(x);
while(ch[x][0]) pushdown(x), x = ch[x][0];
return x;
}
inline void split(int x, int y){//函数功能:把x到y的路径抠出来
makeroot(x); access(y); splay(y);
//先把x弄成原图的根
//再把y和根的路径弄成重链
//那么就是y及其左子树存储的信息了
}
inline void link(int x,int y){
makeroot(x);
// if (findroot(y) == x) return; //如果保证不相连,可以去掉.
f[x] = y;
}
inline void cut(int x,int y){
split(x,y);
//保证联通可以去掉 findroot(y) == x
f[x] = ch[y][0] = 0; pushup(y);
}
int n,m,x,y,op,z;
int main() {
scanf("%d%d",&n,&m);
for (int i = 1; i <= n; ++i)
val[i] = 1,mul[i] = 1,sz[i] = 1;
for (int i = 1; i < n; ++i){
scanf("%d%d",&x,&y);
link(x,y);
}
for (int i = 0; i < m; ++i){
scanf("%s",s);
if (s[0] == '+'){
scanf("%d%d%d",&x,&y,&z);
split(x,y);
change(y,1,z);
}else if (s[0] == '-'){
scanf("%d%d",&x,&y); cut(x,y);
scanf("%d%d",&x,&y); link(x,y);
} else if (s[0] == '*'){
scanf("%d%d%d",&x,&y,&z);
split(x,y);
change(y,z,0);
} else {
scanf("%d%d",&x,&y);
split(x,y);
int ans = sum[y];
printf("%d\n",ans);
}
}
return 0;
}