2021.08.01 P3377 左偏树模板
作者:互联网
2021.08.01 P3377 左偏树模板
P3377 【模板】左偏树(可并堆) - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define aa 100010
int n,m,vis[aa],fa[aa];
struct node{
int ls,rs,val,dis;
}a[aa];
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')w=-1;
ch=getchar();
}
while(ch<='9'&&ch>='0'){
s=s*10+ch-'0';
ch=getchar();
}
return s*w;
}
int find(int x){
return fa[x]==x?x:fa[x]=find(fa[x]);
}
int merge(int x,int y){
if(!x||!y)return x+y;
if(a[x].val ==a[y].val?x>y:a[x].val>a[y].val)
swap(x,y);//x<y
a[x].rs =merge(a[x].rs ,y);
if(a[a[x].ls ].dis <a[a[x].rs].dis)
swap(a[x].ls,a[x].rs);
fa[x]=fa[a[x].ls]=fa[a[x].rs]=x;
a[x].dis=a[a[x].rs].dis+1;
return x;
}
void pop(int x){
vis[x]=1;
fa[a[x].ls]=a[x].ls;
fa[a[x].rs]=a[x].rs;
fa[x]=merge(a[x].ls,a[x].rs);
a[x].ls=a[x].rs=a[x].dis=0;
}
int main(){
n=read();m=read();
for(int i=1;i<=n;i++)a[i].val=read(),fa[i]=i;
a[0].dis=-1;
while(m--){
int x;
x=read();
if(x==1){
int u,v,ui,vi;
u=read();v=read();
if(vis[u]||vis[v])continue;
ui=find(u);vi=find(v);
if(ui!=vi)fa[ui]=fa[vi]=merge(ui,vi);
}else if(x==2){
int u,ui;
u=read();
if(vis[u]){
cout<<"-1"<<endl;
continue;
}
ui=find(u);
cout<<a[ui].val<<endl;
pop(ui);
}
}
//for(int i=1;i<=n;i++)cout<<fa[i]<<" ";cout<<endl;//
return 0;
}
标签:aa,ch,val,int,2021.08,fa,P3377,左偏 来源: https://www.cnblogs.com/eleveni/p/15086768.html