我和第二篇题解写的差不多。最后一个点为什么会被卡???
查看原帖
我和第二篇题解写的差不多。最后一个点为什么会被卡???
248896
genshy楼主2020/7/4 10:55
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 1e6+7;
int n,m,opt,x,y;
int fa[N];
struct node{
	int val, dis;
	int lc,rc;
}tr[N];
int inline read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
void swap(int &x,int &y){int t=x;x=y,y=t;}
int find(int x){
	while(fa[x]) x = fa[x];
	return x;
}
int merage(int x,int y){
	if(x == 0 || y == 0) return x+y;
	if(tr[x].val > tr[y].val || (tr[x].val == tr[y].val && x > y)){
		swap(x,y);
	}
	tr[x].rc = merage(tr[x].rc,y);
	fa[tr[x].rc] = x;
	if(tr[tr[x].lc].dis < tr[tr[x].rc].dis) swap(tr[x].lc,tr[x].rc);
	tr[x].dis = tr[tr[x].rc].dis +1;
	return x;
}
void del(int x){
	tr[x].val = -1;
	fa[tr[x].lc] = fa[tr[x].rc] = 0;
	merage(tr[x].lc,tr[x].rc);
}
int main(){
	n = read(), m = read();
	tr[0].dis = -1;
	for(int i = 1; i <= n; i++){
        tr[i].val = read();
	}
	while(m--){
		opt = read();
		if(opt == 1){
			x = read(); y = read();
			if(tr[x].val == -1 || tr[y].val == -1) continue;
			if(x == y) continue;
			merage(find(x),find(y));
		}
		else{
			x = read();
			if(tr[x].val == -1) cout<<-1<<endl;
			else{
				printf("%d\n",tr[find(x)].val);
				del(find(x));
			}
		}
	}
	return 0;
}
2020/7/4 10:55
加载中...