题目描述
Once in a forest, there lived N aggressive monkeys. At the beginning, they each does things in its own way and none of them knows each other. But monkeys can’t avoid quarrelling, and it only happens between two monkeys who does not know each other. And when it happens, both the two monkeys will invite the strongest friend of them, and duel. Of course, after the duel, the two monkeys and all of there friends knows each other, and the quarrel above will no longer happens between these monkeys even if they have ever conflicted.

Assume that every money has a strongness value, which will be reduced to only half of the original after a duel(that is, 10 will be reduced to 5 and 5 will be reduced to 2).

And we also assume that every monkey knows himself. That is, when he is the strongest one in all of his friends, he himself will go to duel.

一开始有n只孤独的猴子,然后他们要打m次架,每次打架呢,都会拉上自己朋友最牛叉的出来跟别人打,打完之后战斗力就会减半,每次打完架就会成为朋友(正所谓不打不相识o(∩_∩)o )。问每次打完架之后那俩猴子最牛叉的朋友战斗力还有多少,若朋友打架就输出-1.

输入格式
There are several test cases, and each case consists of two parts.

First part: The first line contains an integer N(N<=100,000), which indicates the number of monkeys. And then N lines follows. There is one number on each line, indicating the strongness value of ith monkey(<=32768).

Second part: The first line contains an integer M(M<=100,000), which indicates there are M conflicts happened. And then M lines follows, each line of which contains two integers x and y, indicating that there is a conflict between the Xth monkey and Yth.

有多组数据

输出格式
For each of the conflict, output -1 if the two monkeys know each other, otherwise output the strength value of the strongest monkey among all of its friends after the duel.

输入输出样例
输入 #1复制

5
20
16
10
10
4
5
2 3
3 4
3 5
4 5
1 5
输出 #1复制
8
5
5
-1
10


很明显的一道 可并堆+并查集 。当然 无旋treap也可以做,但是代码量大一些。

我们通过并查集维护当前的猴子所在的集合。

用左偏树维护最大值,并且支持堆合并。然后就ok了。

然后每次就是取出堆顶,踢出去,值减半,然后放回来,最后合并两堆。


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=1e5+10;
int n,m;
int val[N],f[N],ch[N][2],dis[N];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
int merge(int x,int y){
	if(!x||!y)	return x+y;
	if(val[x]<val[y])	swap(x,y);
	ch[x][1]=merge(ch[x][1],y);
	if(dis[ch[x][1]]>dis[ch[x][0]])	swap(ch[x][1],ch[x][0]);
	dis[x]=dis[ch[x][1]]+1;
	return x;
}
signed main(){
	while(cin>>n){
		dis[0]=-1;
		for(int i=1;i<=n;i++)	ch[i][0]=ch[i][1]=dis[i]=0;
		for(int i=1;i<=n;i++)	scanf("%d",&val[i]),f[i]=i; cin>>m;
		while(m--){
			int x,y;	cin>>x>>y; int fa=find(x),fb=find(y);
			if(fa==fb){puts("-1"); continue;}
			val[fa]>>=1;
			int rt=merge(ch[fa][0],ch[fa][1]); 
			ch[fa][0]=ch[fa][1]=dis[fa]=0;
			int art=merge(rt,fa);
			f[rt]=f[fa]=art;
			val[fb]>>=1;
			rt=merge(ch[fb][0],ch[fb][1]);
			ch[fb][0]=ch[fb][1]=dis[fb]=0;
			int brt=merge(rt,fb);
			f[rt]=f[fb]=brt;
			rt=merge(art,brt);
			f[art]=f[brt]=rt;
			printf("%d\n",val[rt]);
		}
	}
	return 0;
}