# BZOJ 1056 [HAOI2008] 排名系统 Tire树+Treap(Splay)

Trie树+Treap练手题233

#include <cstdio>
#include <cstdlib>
#include <cstring>
#define Max(a,b) (b<a?a:b)
#define Min(a,b) (a<b?a:b)
using namespace std;
int tim_cnt,top=0;
char nam[250001][12];
struct Point{
int v,t,ord;
Point(){v=t=ord=0;}
bool operator == (const Point &x) const { return v==x.v && t==x.t;}
bool operator < (const Point &x) const{ return v<x.v || v==x.v && t>x.t; }
};
struct Node{
Point v;
Node *ch[2];
int r,s;
Node(){ch[0]=ch[1]=NULL; r=0; s=1; }
int cmp(Point x){
if(v==x) return -1;
return x < v ? 0 : 1 ;
}
void maintain(){
s=1;
if(ch[0]!=NULL) s+=ch[0]->s;
if(ch[1]!=NULL) s+=ch[1]->s;
return ;
}
}*Treap;
void Rotate(Node* &o,int d){
Node* k=o->ch[d^1]; o->ch[d^1]=k->ch[d]; k->ch[d]=o;
o->maintain(); k->maintain(); o=k;
return ;
}
void Insert(Node* &o,Point x){
if(o==NULL) {o=new Node(); o->v=x; o->r=rand(); o->s=1; }
else{
int d=o->cmp(x);
Insert(o->ch[d],x);
if(o->ch[d]->r > o->r) Rotate(o,d^1);
else o->maintain();
}
return ;
}
void Remove(Node* &o,Point x){
int d=o->cmp(x);
if(d==-1){
Node *u=o;
if(o->ch[0]!=NULL && o->ch[1]!=NULL) {
int d2= o->ch[0]->r > o->ch[1]->r ? 1 : 0;
Rotate(o,d2); Remove(o->ch[d2],x);
}
else {
if(o->ch[0]==NULL) o=o->ch[1];
else o=o->ch[0];
delete u;
}
}
else Remove(o->ch[d],x);
if(o!=NULL) o->maintain();
}
int Rank(Node* &o,Point x){
int d=o->cmp(x);
if(d==-1) return o->ch[0]==NULL ? 1 : o->ch[0]->s+1;
if(d==0)  return Rank(o->ch[0],x);
return (o->ch[0]==NULL ? 0 : o->ch[0]->s)+1+Rank(o->ch[1],x);
}
int Kth(Node* &o,int k){
if(o==NULL || k<=0 || k>o->s) return 0;
int s= o->ch[1]==NULL ? 0 : o->ch[1]->s;
if(k==s+1) return o->v.ord;
else if(k<=s) return Kth(o->ch[1],k);
else return Kth(o->ch[0],k-s-1);
}
struct Trie{
Trie* ch[26];
Point p;
Trie(){for(int i=0;i<26;i++) ch[i]=NULL;  }
void Ins(char T[],Trie* x,int y){
int len=strlen(T);
for(int i=1;i<len;i++){
int z=T[i]-'A';
if(x->ch[z]==NULL) x->ch[z]=new Trie();
x=x->ch[z];
}
if(x->p.ord) Remove(Treap,x->p);
else{
top++;
for(int i=1;i<len;i++) nam[top][i-1]=T[i];
x->p.ord=top;
}
x->p.v=y; x->p.t=++tim_cnt;
Insert(Treap,x->p);
}
void Query(char T[],Trie *x){
int len=strlen(T);
for(int i=1;i<len;i++){
int z=T[i]-'A';
if(x->ch[z]==NULL) return ;
x=x->ch[z];
}
if(!x->p.ord) return ;
printf("%d\n",top-Rank(Treap,x->p)+1);
}
}*trie;
char s[15];
inline bool isalpha(char c){return c>='A' && c<='Z'; }
int main(){
trie = new Trie();
int T;
scanf("%d",&T);
while(T--){
scanf("%s",s);
if(s[0]=='+'){
int x;
scanf("%d",&x);
trie->Ins(s,trie,x);
}
if(s[0]=='?'){
if(isalpha(s[1])) trie->Query(s,trie);
else{
int x=0;
int len=strlen(s);
for(int i=1;i<len;i++) {
x*=10;
x+=s[i]-'0';
}
len=Min(top,x+9);
int k;
for(int i=x;i<len;i++) k=Kth(Treap,i),printf("%s ",nam[k]);
k=Kth(Treap,len); printf("%s\n",nam[k]);
}
}
}
return 0;
}

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客