题目链接:http://wikioi.com/problem/1285/
解题思路:两颗treap树,宠物一棵,人一棵分别查找,加一个是否为empty的函数。
解题代码:

1 // File Name: 1852.cpp 2 // Author: darkdream 3 // Created Time: 2014年07月23日 星期三 09时03分05秒 4 5 #include<vector> 6 #include<list> 7 #include<map> 8 #include<set> 9 #include<deque> 10 #include<stack> 11 #include<bitset> 12 #include<algorithm> 13 #include<functional> 14 #include<numeric> 15 #include<utility> 16 #include<sstream> 17 #include<iostream> 18 #include<iomanip> 19 #include<cstdio> 20 #include<cmath> 21 #include<cstdlib> 22 #include<cstring> 23 #include<ctime> 24 25 using namespace std; 26 const int inf = ~0U>>1; 27 int ans; 28 int s; 29 class treap{ 30 struct node{ 31 int value,key,size; 32 node(int v, node *n):value(v) 33 { 34 c[0] = c[1] = n ; 35 size = 1; 36 key = rand() - 1; 37 } 38 void rz(){ 39 size = c[0]->size + c[1]->size +1; 40 } 41 node *c[2]; 42 }*root,*null; 43 void rot(node *&t,bool d) 44 { 45 node *c = t->c[d]; 46 t->c[d] = c->c[!d]; 47 c->c[!d] = t; 48 t->rz();c->rz(); 49 t = c ; 50 } 51 void insert(node *&t, int x) 52 { 53 if(t == null) { 54 t = new node(x,null); 55 return ; 56 } 57 if(x == t->value) 58 return ; 59 bool d = x > t->value; 60 insert(t->c[d],x); 61 if(t->c[d]->key < t->key) 62 rot(t,d); 63 else t->rz(); 64 } 65 void Delete(node *&t ,int x) 66 { 67 if(t == null) return ; 68 if(t->value == x) 69 { 70 bool d = t->c[1]->key < t->c[0]->key; //两个字子节点 71 if(t->c[d] == null) 72 { 73 delete t; 74 t = null; 75 return; 76 } 77 rot(t,d); 78 Delete(t->c[!d],x); 79 }else{ 80 bool d = x>t->value; 81 Delete(t->c[d],x); 82 } 83 t->rz(); 84 } 85 void find(node *t , int x){ 86 if(t == null) 87 return; 88 if(abs(x-t->value) < ans || (abs(x-t->value) == ans && t->value < x)) 89 { 90 ans = abs(x-t->value); 91 s = t->value; 92 } 93 if(x > t->value) 94 { 95 find(t->c[1],x); 96 }else{ 97 find(t->c[0],x); 98 } 99 } 100 public: 101 treap(){ 102 null = new node(0,0); 103 null ->size = 0 ; 104 null ->key = inf; 105 root = null; 106 } 107 void ins(int x) 108 { 109 insert(root , x); 110 } 111 void del(int x) 112 { 113 Delete(root,x); 114 } 115 void fin(int x) 116 { 117 find(root,x); 118 } 119 int isempty() 120 { 121 if(root == null) 122 return 1; 123 return 0; 124 } 125 }; 126 int main(){ 127 int n ; 128 scanf("%d",&n); 129 int sum = 0 ; 130 treap R,G; 131 srand(time(NULL)); 132 for(int i = 1;i <= n;i ++) 133 { 134 int st; 135 int x; 136 scanf("%d %d",&st,&x); 137 ans = inf ; 138 if(st == 0 ) 139 { 140 if(R.isempty()) 141 { 142 G.ins(x); 143 }else{ 144 R.fin(x); 145 R.del(s); 146 sum = (sum + ans) % 1000000; 147 // printf("***%d ",s); 148 } 149 }else { 150 if(G.isempty()) 151 { 152 R.ins(x); 153 }else{ 154 G.fin(x); 155 G.del(s); 156 sum = (sum + ans) % 1000000; 157 // printf("***%d ",s); 158 } 159 } 160 } 161 printf("%d ",sum); 162 return 0; 163 }
本来是想用cxlove的代码去交一下对比一下时间的了,没想到他的10组wa了9组,,不知道是不是我贴的姿势不对。