# hdu1512&洛谷p1456

## 题目描述

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.

## 输入输出格式

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.

## 输入输出样例

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

8
5
5
-1
10


## 说明

#include<bits/stdc++.h>
using namespace std;
int a[200000],ch[200000][2],f[200000],d[200000];
int merge(int x,int y){
if(!x||!y)return x+y;
if(a[x]<a[y])swap(x,y);
ch[x][1]=merge(ch[x][1],y);
f[ch[x][1]]=x;
if(d[ch[x][0]]<d[ch[x][1]])swap(ch[x][0],ch[x][1]);
d[x]=d[ch[x][1]]+1;
return x;
}
int gf(int t){
while(f[t])t=f[t];
return t;
}
int pop(int x){
int l=ch[x][0],r=ch[x][1];
a[x]/=2;
f[ch[x][0]]=0;f[ch[x][1]]=0;
ch[x][0]=0;ch[x][1]=0;
d[x]=0;
return merge(l,r);
}
int main(){
int n,m,i,t,k,x,y,x1,y1;
while(~scanf("%d",&n)){
memset(f,0,sizeof(f));
memset(d,0,sizeof(d));
memset(ch,0,sizeof(ch));
d[0]=-1;
for(i=1;i<=n;i++)scanf("%d",&a[i]);
scanf("%d",&m);
for(i=1;i<=m;i++){
scanf("%d%d",&t,&k);
x=gf(t);y=gf(k);
if(x==y){
printf("-1\n");
continue;
}
x1=pop(x);y1=pop(y);
x=merge(x1,x);y=merge(y1,y);
printf("%d\n",a[merge(x,y)]);
}
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：hdu1512&洛谷p1456 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)