标签:
水题
用set和splay都写了一下
set版
1 #include <set> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 const int maxn = 300005; 7 struct node 8 { 9 int val,name; 10 bool operator <(const node &rhs)const{ 11 return val<rhs.val; 12 } 13 }; 14 15 int main() 16 { 17 set<node>s; 18 int op,b,c; 19 while(~scanf("%d",&op)&&op){ 20 if(op==1){ 21 scanf("%d%d",&b,&c); 22 s.insert((node){c,b}); 23 } 24 else { 25 if(s.empty())printf("0\n"); 26 else { 27 if(op==2){ 28 set<node>::iterator it = s.end(); 29 it--; 30 printf("%d\n",(*it).name); 31 s.erase(it); 32 } 33 else { 34 set<node>::iterator it = s.begin(); 35 printf("%d\n",(*it).name); 36 s.erase(it); 37 } 38 } 39 } 40 } 41 return 0; 42 }
splay
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 const int maxn = 200005; 6 int fa[maxn],son[2][maxn],val[maxn],name[maxn]; 7 int root,tot,cnt; 8 void rota(int w,int x){ 9 int y = fa[x]; 10 son[!w][y] = son[w][x]; 11 if(son[w][x])fa[son[w][x]] = y; 12 fa[x] = fa[y]; 13 if(fa[y])son[y==son[1][fa[y]]][fa[y]] = x; 14 fa[y] = x; 15 son[w][x] = y; 16 } 17 void splay(int x,int y){ 18 while(fa[x]!=y){ 19 if(fa[fa[x]]==y)rota(x==son[0][fa[x]],x); 20 else { 21 int w = fa[x]==son[0][fa[fa[x]]]; 22 if(x==son[w][fa[x]]){ 23 rota(!w,x);rota(w,x); 24 } 25 else { 26 rota(w,fa[x]);rota(w,x); 27 } 28 } 29 } 30 if(y==0)root = x; 31 } 32 void Ins(int v){ 33 int x = root; 34 while(1){ 35 if(v<val[x]){ 36 if(son[0][x])x = son[0][x]; 37 else break; 38 } 39 else { 40 if(son[1][x])x = son[1][x]; 41 else break; 42 } 43 } 44 fa[++tot] = x; 45 val[tot] = v; 46 if(v<val[x])son[0][x] = tot; 47 else son[1][x] = tot; 48 splay(tot,0); 49 } 50 int getMax(){ 51 int x = root; 52 while(1){ 53 if(son[1][x])x = son[1][x]; 54 else break; 55 } 56 return x; 57 } 58 int getMin(){ 59 int x = root; 60 while(1){ 61 if(son[0][x])x = son[0][x]; 62 else break; 63 } 64 return x; 65 } 66 void Del(int x){ 67 splay(x,0); 68 int y = son[0][x],z = son[1][x]; 69 if(y==0&&z==0){root = 0;return;} 70 while(son[1][y])y = son[1][y]; 71 while(son[0][z])z = son[0][z]; 72 if(y)splay(y,0); 73 if(z)splay(z,y); 74 if(y==0){son[0][z] = 0;return;} 75 if(z==0){son[1][y] = 0;return;} 76 son[0][z] = 0; 77 } 78 int main() 79 { 80 int op,a,b; 81 while(~scanf("%d",&op)&&op){ 82 if(op==1){ 83 scanf("%d%d",&a,&b); 84 if(cnt==0)val[root = ++tot] = b; 85 else Ins(b); 86 name[tot] = a; 87 cnt++; 88 } 89 else { 90 if(cnt==0)printf("%d\n",0); 91 else { 92 int x; 93 if(op==2)x = getMax(); 94 else x = getMin(); 95 printf("%d\n",name[x]); 96 Del(x); 97 cnt--; 98 } 99 } 100 } 101 return 0; 102 }
标签:
原文地址:http://www.cnblogs.com/GJKACAC/p/4716272.html