P1456 Monkey King


弱智的可能有多组读入输出


#include<bits/stdc++.h>
using namespace std;
const int bow=100100;
int val[bow],lc[bow],rc[bow],f[bow],d[bow],n,m;
int find(int x){if(f[x]==x)return x;return f[x]=find(f[x]);}
int merge(int x,int y)
{
    if(!x||!y)return x+y;
    if(val[x]<val[y])swap(x,y);
    rc[x]=merge(rc[x],y);
    if(d[rc[x]]>d[lc[x]])swap(rc[x],lc[x]);
    d[x]=rc[x]+1;
    return x;
}
int main()
{    while(~scanf("%d",&n))
    {
    for(int i=1;i<=n;i++){cin>>val[i];f[i]=i;d[i]=lc[i]=rc[i]=0;}
    cin>>m;
    d[0]=-1;
    int cnt=0;
    while(m--)
    {
        cnt++;
        int x,y;
        cin>>x>>y;
        x=find(x),y=find(y);
        if(x==y){cout<<-1<<endl;continue;}
        val[x]/=2;val[y]/=2;
        int t1=merge(lc[x],rc[x]),t2=merge(rc[y],lc[y]);
        d[x]=lc[x]=rc[x]=0;d[y]=lc[y]=rc[y]=0;
        int t3=merge(t1,x),t4=merge(t2,y);
        f[x]=f[t1]=t3;f[y]=f[t2]=t4;
        int pt=merge(t3,t4);
        f[t3]=f[t4]=pt;
        cout<<val[pt]<<endl;
    }
    }
}
原文地址:https://www.cnblogs.com/SFWR-YOU/p/11514842.html