1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| namespace Treap{
int sz[N],rd[N],ch[N][2],val[N],cnt[N],idx,rt;
inline void push(int x){sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+cnt[x];}
inline void rotate(int& p,int k){ int x=ch[p][k^1]; ch[p][k^1]=ch[x][k]; ch[x][k]=p; push(p),push(x); p=x; }
void ins(int& x,int v){ if(!x){ x=++idx; sz[x]=cnt[x]=1; ch[x][0]=ch[x][1]=0; val[x]=v; rd[x]=rand(); return ; } if(v==val[x]){ cnt[x]++,sz[x]++; return ; } int k=v>val[x]; ins(ch[x][k],v); if(rd[x]<rd[ch[x][k]]) rotate(x,k^1); push(x); }
void del(int& x,int v){ if(!x) return ; if(v<val[x]) del(ch[x][0],v); else if(v>val[x]) del(ch[x][1],v); else { if(!ch[x][0] && !ch[x][1]){ cnt[x]--,sz[x]--; if(cnt[x]==0) x=0; } else if(ch[x][0] && !ch[x][1]){ rotate(x,1); del(ch[x][1],v); } else if(!ch[x][0] && ch[x][1]){ rotate(x,0); del(ch[x][0],v); } else { int k=rd[ch[x][0]]>rd[ch[x][1]]; rotate(x,k); del(ch[x][k],v); } } push(x); }
int rk(int x,int v){ if(!x) return 0; if(v==val[x]) return sz[ch[x][0]]+1; if(v<val[x]) return rk(ch[x][0],v); else return sz[ch[x][0]]+cnt[x]+rk(ch[x][1],v); }
int kth(int x,int k){ if(!x) return 0; if(k<=sz[ch[x][0]]) return kth(ch[x][0],k); else if(k>sz[ch[x][0]]+cnt[x]) return kth(ch[x][1],k-sz[ch[x][0]]-cnt[x]); else return val[x]; }
int pre(int x,int v){ if(!x) return -inf; if(v<=val[x]) return pre(ch[x][0],v); else return max(val[x],pre(ch[x][1],v)); }
int nxt(int x,int v){ if(!x) return inf; if(v>=val[x]) return nxt(ch[x][1],v); else return min(val[x],nxt(ch[x][0],v)); }
}
|