数据结构(左偏树):HDU 1512 Monkey King

Monkey King

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4714    Accepted Submission(s): 2032

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
 
 
  注意初始值:dis[0]=-1……
  因为delete掉的点还要在用,所以在delete时要清空ls和rs……
  
  这两个细节是致命的。
 #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=;
int ch[maxn][],dis[maxn],key[maxn];
int fa[maxn],rt[maxn],n,m;
void Init(){
dis[]=-;
for(int i=;i<=n;i++){
fa[i]=i;rt[i]=i;dis[i]=;
ch[i][]=ch[i][]=;
}
} int Merge(int x,int y){
if(!x||!y)return x|y;
if(key[x]<key[y])swap(x,y);
ch[x][]=Merge(ch[x][],y);
if(dis[ch[x][]]>dis[ch[x][]])
swap(ch[x][],ch[x][]);
dis[x]=dis[ch[x][]]+;
return x;
} void Delete(int x){
int tmp=rt[x];
rt[x]=Merge(ch[rt[x]][],ch[rt[x]][]);
ch[tmp][]=ch[tmp][]=;
} int Find(int x){
return x==fa[x]?x:fa[x]=Find(fa[x]);
} int main(){
while(scanf("%d",&n)!=-){
Init();
for(int i=;i<=n;i++)
scanf("%d",&key[i]);
int x,y;
scanf("%d",&m);
while(m--){
scanf("%d%d",&x,&y);
x=Find(x);y=Find(y);
if(x==y)
printf("-1\n");
else{
int ta=rt[x],tb=rt[y];
Delete(x);key[ta]/=;rt[x]=Merge(rt[x],ta);
Delete(y);key[tb]/=;rt[y]=Merge(rt[y],tb);
fa[y]=x;rt[x]=Merge(rt[x],rt[y]);
printf("%d\n",key[rt[x]]);
}
}
}
return ;
}
 
 
上一篇:【python】——购物车


下一篇:让我们一起Go(十)