[BZOJ2733][HNOI2012][启发式合并][平衡树]永无乡

题意

给定n个点,每个点有权值,操作会联通某两个点的联通块,或询问某联通块中的第k大的点。


对每个点维护一个平衡树,对于联通的操作启发式合并,把size小的树每个点暴力拆开,插入到size大的树中。

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#define N 200010

using namespace std;

int n,m,x,y,q;
char op;
struct lef{
  lef *fa,*ch[2];
  int sz,r,w,g;
}p[N],*rt,*u,*v,*city[N];

inline void updat(lef *x){
  if(!x) return; x->sz=1;
  if(x->ch[0]) x->sz+=x->ch[0]->sz;
  if(x->ch[1]) x->sz+=x->ch[1]->sz;
}

inline void *reborn(lef *x){
  x->fa=x->ch[0]=x->ch[1]=NULL;
  x->sz=1;
}

inline void rot(lef *x){
  lef *y=x->fa,*z=y->fa; int lor=x==y->ch[1];
  if(z) z->ch[z->ch[1]==y]=x; x->fa=z;
  if(y->ch[lor]=x->ch[lor^1]) y->ch[lor]->fa=y;
  (x->ch[lor^1]=y)->fa=x; updat(y); updat(x);
}

inline void InserT(lef *&x,lef *y){
  if(!x){x=y;return ;}
  x->sz++;
  if(x->w>y->w){
    InserT(x->ch[0],y);
    x->ch[0]->fa=x;
    if(x->r>x->ch[0]->r)
      rot(x->ch[0]);
  }
  else{
    InserT(x->ch[1],y);
    x->ch[1]->fa=x;
    if(x->r>x->ch[1]->r)
      rot(x->ch[1]);
  }
}

inline char C(){
  static char buf[100000],*p1=buf,*p2=buf;
  if(p1==p2){
    p2=(p1=buf)+fread(buf,1,100000,stdin);
    if(p1==p2) return EOF;
  }
  return *p1++;
}

inline void reaD(int &x){
  char Ch=C();x=0;
  for(;Ch>'9'||Ch<'0';Ch=C());
  for(;Ch>='0'&&Ch<='9';x=x*10+Ch-'0',Ch=C());
}

inline lef *Getrt(lef *x){
  if(!x) return NULL;
  while(x->fa) x=x->fa;
  return x;
}

void merge(lef *x,lef *y){
  if(x->ch[0]) merge(x->ch[0],y);
  if(x->ch[1]) merge(x->ch[1],y);
  reborn(x);
  InserT(y,x);
}

int check(lef *x,int y){
  int k=1;
  if(x->ch[0]) k+=x->ch[0]->sz;
  if(k==y) return x->g;
  if(k<y) return check(x->ch[1],y-k);
  else return check(x->ch[0],y);
}

int main(){
  freopen("2733.in","r",stdin);
  freopen("2733.out","w",stdout);
  reaD(n);reaD(m);
  for(int i=1;i<=n;i++){
    city[i]=&p[i];
    reaD(city[i]->w);
    city[i]->r=rand();
    city[i]->g=i;
    city[i]->sz=1;
  }
  for(int i=1;i<=m;i++){
    reaD(x); reaD(y);
    u=Getrt(city[x]);
    v=Getrt(city[y]);
    if(u==v) continue;
    if(u->sz>v->sz) swap(u,v);
    merge(u,v);
  }
  reaD(q);
  for(int i=1;i<=q;i++){
    while((op=C())!='Q'&&op!='B');
    if(op=='B'){
      reaD(x);reaD(y);
      u=Getrt(city[x]);
      v=Getrt(city[y]);
      if(u==v) continue;
      if(u->sz>v->sz) swap(u,v);
      merge(u,v);
    }
    else{
      reaD(x);reaD(y);
      u=Getrt(city[x]);
      if(!u||y>u->sz) puts("-1");
      else printf("%d\n",check(u,y));
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值