洛谷3377【【模板】左偏树】--左偏树&并查集

【链接】
洛谷3377

【题目大意】
左偏树模板

【解题报告】
详见左偏树

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100005;
int n,m,fa[maxn];
bool vis[maxn];
struct Ztree
{
    Ztree* son[2];
    int x,id,dis;
}a[maxn],*ro[maxn],*Null=a,*len=Null;
inline int Read()
{
    int res=0;
    char ch=getchar();
    while (ch<'0'||ch>'9') ch=getchar();
    while (ch>='0'&&ch<='9') res=res*10+ch-48,ch=getchar();
    return res;
}
void New(Ztree* &k,int x,int i)
{
    k=++len; k->x=x; k->id=i; k->dis=0; k->son[0]=k->son[1]=Null;
}
Ztree* Join(Ztree* a,Ztree* b)
{
    if (a==Null) return b; if (b==Null) return a;
    if (b->x<a->x||(b->x==a->x&&b->id<a->id)) swap(a,b);
    a->son[1]=Join(a->son[1],b);
    if (a->son[0]->dis<a->son[1]->dis) swap(a->son[0],a->son[1]);
    if (a->son[1]==Null) a->dis=0; else a->dis=a->son[1]->dis+1;
    return a;
}
Ztree* Delete(Ztree* a)
{
    return Join(a->son[0],a->son[1]);
}
int Getfa(int x)
{
    if (x==fa[x]) return x;
    fa[x]=Getfa(fa[x]);
    return fa[x];
}
int main()
{
    n=Read(); m=Read();
    for (int i=1,x; i<=n; i++) x=Read(),fa[i]=i,New(ro[i],x,i);
    memset(vis,0,sizeof(vis));
    for (int i=1,x,y,t; i<=m; i++)
    {
        t=Read(); 
        if (t==1)
         {
            x=Read(); y=Read();
            if (vis[x]||vis[y]) continue;
            x=Getfa(x); y=Getfa(y);
            if (x==y) continue;
            Ztree* now=Join(ro[x],ro[y]);
            ro[now->id]=now; fa[x]=fa[y]=now->id;
         }
            else
         {
            x=Read();
            if (vis[x]) {printf("-1\n"); return 0;}
            x=Getfa(x); printf("%d\n",ro[x]->x);
            Ztree* now=Delete(ro[x]); vis[x]=1;
            if (now==Null) continue;
            ro[now->id]=now; fa[x]=fa[now->id]=now->id;
         }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值