bzoj1455: 罗马游戏

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1455

思路:左偏树练习题

用并查集维护连通,然后开个数组记录每个人是否已被杀死,用可并堆支持合并和求最小值

左偏树是一种支持合并的堆,写起来比手写堆还要短...

只有一个操作,merge(a,b),就是把a,b合并...

具体构建参见论文:http://wenku.baidu.com/link?url=CPzCT6_74LbTMczlGZL8oB3wa9vivG2U9pTEXFMDLuolIvRgp_cbi2BHwT3NXhher9qgjXWEoB8PG3P8QeT2A22Zv3L5oi7nSADoPG08ofa


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
const int maxn=1000010;
using namespace std;
int n,m,fa[maxn];bool die[maxn];char op[2];
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
void read(int &x){
	char ch;
	for (ch=getchar();!isdigit(ch);ch=getchar());
	for (x=0;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
}
struct Ltree{
	int tot,l[maxn],r[maxn],dis[maxn],v[maxn];
	void newnode(int val){v[++tot]=val,l[tot]=r[tot]=dis[tot]=0;}
	int merge(int x,int y){
		if (!x) return y;
		if (!y) return x;
		if (v[x]>v[y]) swap(x,y);
		r[x]=merge(r[x],y);
		if (dis[r[x]]>dis[l[x]]) swap(l[x],r[x]);
		dis[x]=dis[r[x]]+1;
		return x;
	}
}h;

int main(){
	scanf("%d",&n);
	for (int i=1,x;i<=n;i++) read(x),h.newnode(x),fa[i]=i;
	scanf("%d",&m);
	for (int i=1,x,y;i<=m;i++){
		scanf("%s",op);
		if (op[0]=='M'){
			scanf("%d%d",&x,&y);
			if (die[x]||die[y]) continue;
			x=find(x),y=find(y);
			if (x!=y) fa[x]=fa[y]=h.merge(x,y);
		}
		else{
			scanf("%d",&x);
			if (die[x]){puts("0");continue;}
			else{
				x=find(x),die[x]=1;
				printf("%d\n",h.v[x]);
				fa[x]=h.merge(h.l[x],h.r[x]);
				fa[fa[x]]=fa[x];
			}
		}
	}
	return 0;
}


posted @ 2016-04-22 15:13  orzpps  阅读(158)  评论(0编辑  收藏  举报