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.
左偏树,修改操作可以在修改之后断开再重新合并自己和左右子树。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int fa[100010],lson[100010],rson[100010],val[100010],hei[100010],
n,m;
int find(int x)
{
return x==fa[x]?x:fa[x]=find(fa[x]);
}
bool init()
{
int i;
if (scanf("%d",&n)==-1) return 0;
for (i=1;i<=n;i++)
scanf("%d",&val[i]);
scanf("%d",&m);
for (i=1;i<=n;i++)
{
fa[i]=i;
lson[i]=rson[i]=hei[i]=0;
}
return 1;
}
int merge(int u,int v)
{
if (u*v==0) return u+v;
if (val[u]<val[v]) swap(u,v);
rson[u]=merge(rson[u],v);
if (hei[lson[u]]<hei[rson[u]]) swap(lson[u],rson[u]);
hei[u]=hei[rson[u]]+1;
return u;
}
void solve()
{
int u,v,x,y,i,t;
while (m--)
{
scanf("%d%d",&u,&v);
if (find(u)==find(v))
{
printf("-1\n");
continue;
}
u=fa[u];
v=fa[v];
val[u]/=2;
val[v]/=2;
x=merge(lson[u],rson[u]);
lson[u]=rson[u]=0;
x=merge(x,u);
y=merge(lson[v],rson[v]);
lson[v]=rson[v]=0;
y=merge(y,v);
t=merge(x,y);
fa[u]=fa[v]=fa[t]=t;
printf("%d\n",val[t]);
}
}
int main()
{
while (init()) solve();
}