您的位置:首页 > 其它

bzoj1455 罗马游戏

2017-08-23 08:37 246 查看
传送门

左偏树。

CODE:

#include<cstdio>
#include<iostream>
using namespace std;
const int N=1e6+10;
struct node
{
int num,dis,id;
node *ch[2];
}pool
,*t
,*null;
int f
;
bool b
;
int n,m,x,y,tot;
inline void getnew(int value,int id)
{
node *now=pool+ ++tot;
now->ch[0]=now->ch[1]=null;
now->num=value,now->id=id;
t[id]=now;
}
inline int find(int n)
{
if(f
!=n) f
=find(f
);
return f
;
}
node *merge(node *x,node *y)
{
if(x==null) return y;
if(y==null) return x;
if(x->num>y->num||(x->num==y->num&&x->id>y->id)) swap(x,y);
x->ch[1]=merge(x->ch[1],y);
if(x->ch[0]->dis<x->ch[1]->dis) swap(x->ch[0],x->ch[1]);
x->dis=x->ch[1]->dis+1;
return x;
}
inline void Merge(int x,int y)
{
if(b[x]||b[y]) return;
x=find(x),y=find(y);
if(x==y) return;
node *t1=t[x],*t2=t[y];
node *root=merge(t1,t2);
f[t1->id]=f[t2->id]=root->id;
}
inline int del(int x)
{
if(b[x]) return 0;
node *root=t[find(x)];
int ans=root->num;
b[root->id]=1;
node *newroot=merge(root->ch[0],root->ch[1]);
if(newroot!=null)
{
f[root->id]=f[newroot->id]=newroot->id;
if(newroot->ch[0]!=null) f[newroot->ch[0]->id]=newroot->id;
if(newroot->ch[1]!=null) f[newroot->ch[1]->id]=newroot->id;
}
return ans;
}
int main()
{
null=pool;
null->ch[0]=null->ch[1]=null;
null->dis=-1;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&x),getnew(x,i);
for(int i=1;i<=n;i++)
f[i]=i;
scanf("%d",&m);
while(m--)
{
char c=getchar();
while(c!='M'&&c!='K') c=getchar();
if(c=='M') scanf("%d%d",&x,&y),Merge(x,y);
else scanf("%d",&x),printf("%d\n",del(x));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  左偏树 bzoj