Monkey King (and can stack)

The meaning of problems

There are n monkeys, beginning not know each other, each have two monkeys to fight, they got most powerful monkey they know to help them fight (however they see them), so after a fight monkeys ( not theater) force value is reduced by half (rounded down), and they also know each other, the value of force at this time asked for their understanding of the most powerful monkey monkey, fight before understanding output -1.

n,m<=100000

answer

And can be directly heap enough for the kick understanding is to merge the two teams, but for the force to reduce the value of how to get?

Directly to the boss kicked out and try again. Specific implementation is the boss ls, rs merger, so he came out, he then merge and ls (rs) heap.

The concrete realization of some details, implemented in the code inside.

#include<bits/stdc++.h>
using namespace std;

const int maxn=100005;
int n,m,a[maxn];
int fa[maxn],ls[maxn],rs[maxn],dis[maxn],val[maxn];

int find(int x){
  return fa[x]==x ? x : find(fa[x]);
}

int merge(int A,int B){
  if(!A) return B;
  if(!B) return A;
  if(val[A]<val[B]) swap(A,B);
  rs[A]=merge(rs[A],B);
  FA [RS [A]] =A;
   IF (DIS [RS [A]]> DIS [LS [A]]) the swap (RS [A], LS [A]);
   IF (! RS [A]) DIS [ a] = 0 ;
   the else DIS [a] = DIS [RS [a]] + . 1 ;
   return a; 
} 

int POP ( int x) { // int because they do not change ls, rs then combined x may he is a leaf node will REs 
  FA [LS [X]] = LS [X]; 
  FA [RS [X]] = RS [X]; 
  FA [X] = X;
   int RET = Merge (LS [X], RS [X ]); 
  LS [X] = RS [X] = 0 ; // obtained above to change the 
  return RET; 
} 

int main () {
  //freopen("testdata.in","r",stdin);
  while(scanf("%d",&n)!=EOF){
    for(int i=1;i<=n;i++){
      scanf("%d",&val[i]);
      fa[i]=i;
      ls[i]=rs[i]=dis[i]=0;
    }
    scanf("%d",&m);
    for(int i=1;i<=m;i++){
      int x,y;
      scanf("%d%d",&x,&y);
      int dx=find(x),dy=find(y);
      if(dx==dy){printf("-1\n");continue;}
      //printf("*--------%d %d------------*\n",dx,dy);
      int xx=pop(dx),yy=pop(dy);
      //printf("*---------%d %d------*\n",xx,yy);
      val[dx]>>=1;
      val[dy]>>=1;
      merge(dx,find(xx));
      merge(dy,find(yy));
      merge(find(dx),find(dy));
      //for(int j=1;j<=n;j++) printf("%d ",fa[j]);
      //putchar(10);
      printf("%d\n",val[find(dx)]);
    }
  }
  return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/sto324/p/11291530.html