【HDU 1512】Monkey King

【题目】

传送门

Problem Description

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.

Input

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.

Output

For each of the conflict, output -1 if the two monkeys know each other, otherwise output the strongness value of the strongest monkey in all friends of them after the duel.

Sample Input

5
20
16
10
10
4
5
2 3
3 4
3 5
4 5
1 5

Sample Output

8
5
5
-1
10


【分析】

洛谷传送门

题目的翻译就去洛谷上看吧。

然后这也就是一道模板题。

维护大根堆,每次就是找堆顶去打架,打架后合并两个堆就可以了。


【代码】

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100005
using namespace std;
int val[N],dis[N],father[N],son[N][2];
int find(int x)
{
	if(father[x]==x)  return x;
	return father[x]=find(father[x]);
}
int Merge(int x,int y)
{
	if(!x||!y)  return x+y;
	if(val[x]<val[y])  swap(x,y);
	son[x][1]=Merge(son[x][1],y);
	father[son[x][1]]=x;
	if(dis[son[x][0]]<dis[son[x][1]])
	  swap(son[x][0],son[x][1]);
	dis[x]=dis[son[x][1]]+1;
	return x;
}
int Pop(int x)
{
	val[x]/=2;
	int L=son[x][0],R=son[x][1];
	father[L]=L,father[R]=R;
	dis[x]=son[x][0]=son[x][1]=0;
	return Merge(L,R);
}
int solve(int x,int y)
{
	int rtx=Pop(x),rty=Pop(y);
	x=Merge(rtx,x),y=Merge(rty,y);
	return val[Merge(x,y)];
}
int main()
{
	int n,m,i,x,y;
	while(~scanf("%d",&n))
	{
		memset(dis,0,sizeof(dis));
		memset(son,0,sizeof(son));
		for(i=1;i<=n;++i)
		  father[i]=i,scanf("%d",&val[i]);
		scanf("%d",&m);
		for(i=1;i<=m;++i)
		{
			scanf("%d%d",&x,&y);
			x=find(x),y=find(y);
			printf("%d\n",(x==y)?-1:solve(x,y));
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/forever_dreams/article/details/88371896