HDU 1512 Monkey King

来源:互联网 发布:腾讯域名个人备案 编辑:程序博客网 时间:2024/04/30 11:38
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
520161010452 33 43 54 51 5
 

Sample Output
855-110
 

Author
JIANG, Yanyan
 

Source
ZOJ 3rd Anniversary Contest
 

Recommend
linle   |   We have carefully selected several similar problems for you:  1509 1710 1504 1510 1500 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

左偏树~

把dep放到函数外面更新会MLE得很惨,至今不明白为什么……是一种神奇的优化?

对于每次更新a值,把两个领头猴子取出来,除以二,然后把它的左右子树建新树,再把两点插进去,最后输出最高点就可以了~


#include<cstdio>#include<iostream>using namespace std;int n,m,x,y,a[100001],fa[100001],l[100001],r[100001],dep[100001];int findd(int u){return fa[u]==u ? u:fa[u]=findd(fa[u]);}int merge(int u,int v){if(!u) return v;if(!v) return u;if(a[u]<a[v]) swap(u,v);r[u]=merge(r[u],v);fa[r[u]]=u;if(!r[u]) dep[u]=0;else dep[u]=dep[r[u]]+1;if(dep[r[u]]>dep[l[u]]) swap(r[u],l[u]);return u;}int main(){while(scanf("%d",&n)!=EOF){for(int i=1;i<=n;i++) scanf("%d",&a[i]),fa[i]=i,l[i]=0,r[i]=0;scanf("%d",&m);while(m--){scanf("%d%d",&x,&y);int k1=findd(x),k2=findd(y);if(k1==k2){printf("-1\n");continue;}a[k1]/=2;a[k2]/=2;int k=merge(l[k1],r[k1]);l[k1]=r[k1]=0;k1=merge(k,k1);k=merge(l[k2],r[k2]);l[k2]=r[k2]=0;k2=merge(k2,k);k=merge(k1,k2);fa[k1]=fa[k2]=k;printf("%d\n",a[k]);}}return 0;}


1 0