P1456 Monkey King leftist tree

  At first there were only n lonely monkey, and then they want to make the m frame, every fight it, their friends will pull out of most cattle fork to play with others, so after fighting will be halved, each time after the fight it will be friends (the so-called fight before o (∩_∩) o). Asked after the fight that each time after the two most cattle cross the monkey fighting friends how much, if friends fighting on output -1.

 

Leftist tree template put 

The main point is the most troublesome ability decentralized monkeys following subtree after half Zheke

 

Note when and when to update the parent node should update the parent node

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i>=(b);--i)
#define ll long long
#define see(x) (cerr<<(#x)<<'='<<(x)<<endl)
#define pb push_back
#define inf 0x3f3f3f3f
#define CLR(A,v)  memset(A,v,sizeof A)
typedef pair<int,int>pii;
//////////////////////////////////
const int N=5e6+10;

int val[N],lson[N],rson[N],f[N],dis[N];
int find1(int x){return f[x]==x?x:f[x]=find1(f[x]);}

int Merge(int x,int y)
{
    if(!x||!y)return x+y;
    if(val[x]<val[y]||val[x]==val[y]&&x<y)swap(x,y);
    rson[x]=Merge(rson[x],y);
    if(dis[lson[x]]<dis[rson[x]])swap(lson[x],rson[x]);
    f[lson[x]]=f[rson[x]]=f[x]=x;
    dis[x]=dis[lson[x]]+1;
    return x;
}
void pop(intX) {Val [X] = - . 1 ; F [LSON [X]] = LSON [X]; F [rson [X]] = rson [X]; F [X] = the Merge (LSON [X], rson [X]);}
 int n-, m, A, B; 

int Work ( int A, int B) 
{ 
    int X = find1 (A), Y = find1 (B), the root;
     IF (X == Y) return - . 1 ; 

    Val [X] / = 2 ; 
    the root = the Merge (LSON [X], rson [X]); 
    DIS [X] = LSON [X] = rson [X] = 0 ; 
    the root = the Merge (X, the root ); 
    F [the root] = F [X] = the root; // all nodes of the tree are attached to the X 

    Val [Y]/=2;
    root=Merge(lson[y],rson[y]);
    dis[y]=lson[y]=rson[y]=0;
    root=Merge(y,root);
    f[root]=f[y]=root;

    root=Merge(find1(a),find1(b));
    return val[root];
}
int main()
{
    while(cin>>n)
    {
        dis[0]=-1;
        rep(i,1,n)
        scanf("%d",&val[i]),f[i]=i,lson[i]=rson[i]=dis[i]=0;
        cin>>m;
        while(m--)
        cin>>a>>b,printf("%d\n",work(a,b));
    }
    return 0;
}
View Code

Guess you like

Origin www.cnblogs.com/bxd123/p/11345356.html