BZOJ 2631: tree

7 篇文章 0 订阅


其实这题好像也不能说太特别。可能是之前树结构做的不够熟吧。

这类型的题 代码打熟了 就感觉跟线段树差不多了。。。也不算太繁琐

对了,建议用unsigned int,用long long可能会T,反正我用long long是压着时限过去的。。

#include<map>
#include<cmath>
#include<queue>
#include<string>
#include<cstdio>
#include<vector>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define N 100010
#define mod 51061
using namespace std;
int fa[N],n,m,c[N][2],st[N],size[N];
unsigned int jia[N],cheng[N],sum[N],w[N];
bool rev[N];
bool Rt(int x)
{
    if(c[fa[x]][0]==x || c[fa[x]][1]==x)return 0;
    return 1;
}
void cal(int x,int h,int j)
{
    if(!x)return;
    w[x]=(w[x]*h+j)%mod;
    sum[x]=(sum[x]*h+j*size[x])%mod;
    jia[x]=(jia[x]*h+j)%mod;
    cheng[x]=(cheng[x]*h)%mod;
}
void pushup(int x)
{
    int l=c[x][0],r=c[x][1];
    sum[x]=(sum[l]+sum[r]+w[x])%mod;
    size[x]=(size[l]+size[r]+1)%mod;
}
void pushdown(int x)
{
    int l=c[x][0],r=c[x][1];
    if(rev[x])
    {
        rev[x]=0,rev[l]^=1,rev[r]^=1;
        swap(c[x][0],c[x][1]);
    }
    int h=cheng[x],j=jia[x];
    cheng[x]=1,jia[x]=0;
    if(h!=1 || j)
        cal(l,h,j) , cal(r,h,j);
}
void rotate(int x)
{
    int y=fa[x],z=fa[y],a=c[y][1]==x,b=c[z][1]==y,g=c[x][!a];
    if(!Rt(y))c[z][b]=x;
    fa[g]=y,c[y][a]=g;
    fa[y]=x,c[x][!a]=y;
    fa[x]=z;
    pushup(y); pushup(x);
}
void splay(int x)
{
    int top=0,i;
    for(i=x;!Rt(i);i=fa[i])st[++top]=i;
    st[++top]=i;
    for(i=top;i;i--)pushdown(st[i]);
    while(!Rt(x))
    {
        int y=fa[x],z=fa[y],a=c[y][1]==x,b=c[z][1]==y;
        if(!Rt(y))
        {
            if(a==b)rotate(y);
            else rotate(x);
        }
        rotate(x);
    }
}
void access(int x)
{
    int last=0;
    while(x)
    {
        splay(x);
        c[x][1]=last;
        pushup(x);
        last=x,x=fa[x];
    }
}
void make_root(int x)
{
    access(x); splay(x);
    rev[x]^=1;
}
void split(int x,int y)
{
    make_root(x);
    access(y); splay(y);
}
void link(int x,int y)
{
    make_root(x); fa[x]=y;
}
void cut(int x,int y)
{
    split(x,y);
    fa[x]=c[y][0]=0;
}
int main()
{
    int i,n,x,y,p,m;
    char ch[5];
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++) w[i]=sum[i]=cheng[i]=size[i]=1;
    for(i=1;i<n;i++)
        scanf("%d%d",&x,&y),link(x,y);
    while(m--)
    {
        scanf("%s%d%d",ch,&x,&y);
        if(ch[0]=='+')
        {
            scanf("%d",&p);
            split(x,y);
            cal(y,1,p);
        }
        if(ch[0]=='-')
        {
            cut(x,y); scanf("%d%d",&x,&y);
            link(x,y);
        }
        if(ch[0]=='*')
        {
            scanf("%d",&p);
            split(x,y);
            cal(y,p,0);
        }
        if(ch[0]=='/')
        {
            split(x,y);
            printf("%d\n",sum[y]);
        }
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值