hdu1512 Monkey King(左偏树 + 并查集)

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.

InputThere 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.

OutputFor 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.

不知道题意怎么办,那就百度翻译吧,。。。。。。。

算了我来说一下题解:这道题意思是猴子打架的话,就会找他们认识的猴子中最大的来打,然后战斗力减半,然后再合并,最终输出

总共合并后的树上,最大值(也就是堆顶)。

 #include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std; const int NN=1e5+; int n,m,a[NN];
int r[NN],l[NN],d[NN],fa[NN];
bool died[NN]; int find(int num)
{
if (fa[num]!=num) return find(fa[num]);
else return num;
}
int merge(int x,int y)
{
if (!x) return y;
if (!y) return x;
if (a[x]<a[y]) swap(x,y);
r[x]=merge(r[x],y);
fa[r[x]]=x;
if (d[r[x]]>d[l[x]]) swap(r[x],l[x]);
d[x]=d[r[x]]+;
return x;
}
int main()
{
//freopen("1.in","r",stdin);
//freopen("fzy.out","w",stdout);
d[]=-;
while (~scanf("%d",&n))
{
memset(l,,sizeof(r));
memset(r,,sizeof(r));
for (int i=;i<=n;i++)
{
fa[i]=i;
scanf("%d",&a[i]);
}
scanf("%d",&m);
for (int i=;i<=m;i++)
{
int k,u,v;
scanf("%d%d",&u,&v);
int x=find(u),y=find(v);
if (x==y) printf("%d\n",-);
else
{
fa[l[x]]=l[x],fa[r[x]]=r[x]; fa[l[y]]=l[y],fa[r[y]]=r[y];//先各个独立
a[x]/=,a[y]/=;
int t1=merge(l[x],r[x]);
int t2=merge(l[y],r[y]);
fa[t1]=t1,fa[t2]=t2;
l[x]=l[y]=r[x]=r[y]=;//拆开
t1=merge(t1,x);
t2=merge(t2,y);
fa[t1]=t1,fa[t2]=t2;
int t=merge(t1,t2);//再合并
fa[t]=t;
printf("%d\n",a[t]);
}
}
}
}
上一篇:Java设计模式 工厂模式概念解析


下一篇:转换framebuffer实现安卓截图