BZOJ 1180: [CROATIAN2009]OTOCI|动态树

通过解决几道LC题目,作者掌握了如何独立完成裸题的方法,并分享了具体的解题策略。本文深入探讨了算法题目的解题思路和技巧,旨在帮助读者提升编程能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做了几道LCT的题后发现终于会打裸题啦QAQ

#include<cstdio>  
#include<cstdlib>  
#include<cstring>  
#include<cmath>  
#include<queue>  
#include<set>  
#include<map>  
#include<vector>  
#include<algorithm>  
#include<iostream>  
#define N 303333  
using namespace std;  
int sc()  
{  
    int i=0,f=1; char c=getchar();  
    while(c>'9'||c<'0'){if(c=='-')f=-1; c=getchar();}  
    while(c>='0'&&c<='9') i=i*10+c-'0',c=getchar();  
    return i*f;  
}  
bool rev[N];
int v[N],val[N],fa[N],ch[N][2],st[N];
int n,m;
bool Root(int x){return ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x;}
void push_up(int x)
{
    val[x]=val[ch[x][0]]+val[ch[x][1]]+v[x];
}
void push_down(int x)
{
    if(rev[x])
    {
        rev[ch[x][0]]^=1;rev[ch[x][1]]^=1;
        swap(ch[x][1],ch[x][0]);rev[x]=0;
    }
}
void rotate(int x)
{
    int y=fa[x],z=fa[y],l,r;
    l=(ch[y][1]==x);r=l^1;
    if(!Root(y))ch[z][ch[z][1]==y]=x;
    fa[x]=z;fa[y]=x;fa[ch[x][r]]=y;
    ch[y][l]=ch[x][r];ch[x][r]=y;
    push_up(y),push_up(x);
}
void splay(int x)
{
    int top=1;st[1]=x;
    for(int i=x;!Root(i);i=fa[i])st[++top]=fa[i];
    while(top)push_down(st[top--]);
    while(!Root(x))
    {
        int y=fa[x],z=fa[y];
        if(!Root(y))
            if(ch[z][0]==y^ch[y][0]==x)rotate(x);
            else rotate(y);
        rotate(x);
    }
}
void access(int x)
{
    for(int t=0;x;t=x,x=fa[x])
        splay(x),ch[x][1]=t,push_up(x);
}
void make_root(int x)
{
    access(x),splay(x),rev[x]^=1;
}
void link(int x,int y)
{
    make_root(x),fa[x]=y;
}
void cut(int x,int y)
{
    make_root(x),access(y),splay(y);
    fa[x]=ch[y][0]=0,push_up(y);
}
int find(int x)
{
    access(x),splay(x);
    while(ch[x][0])x=ch[x][0],push_down(x);
    return x;
}
int main()
{
    n=sc();
    for(int i=1;i<=n;i++)v[i]=val[i]=sc();
    m=sc();
    while(m--)
    {
        char s[11]; scanf("%s",s);
        if(s[0]=='b')
        {
            int x=sc(),y=sc();
            if(find(x)!=find(y))
            {
                puts("yes");
                link(x,y);
            }
            else puts("no");
        }
        else if(s[0]=='p')
        {
            int x=sc(),y=sc();
            make_root(x),v[x]=y;
            push_up(x);
        }
        else if(s[0]=='e')
        {
            int x=sc(),y=sc();
            int fx=find(x),fy=find(y);
            if(fx==fy)
            {
                make_root(x);
                access(y);
                splay(y);
                printf("%d\n",val[y]);
            }
            else puts("impossible");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值