题目链接:http://codeforces.com/contest/706/problem/D
题意很简单不多说。
把一个数当作二进制插入字典树中,按照xor的性质,1找0,0找1,贪心即可。
注意的是一开始集合中就有0,所以一开始'?'查询时输出他本身。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 //#pragma comment(linker, "/STACK:102400000, 102400000") 2 #include <algorithm> 3 #include <iostream> 4 #include <cstdlib> 5 #include <cstring> 6 #include <cstdio> 7 #include <vector> 8 #include <cmath> 9 #include <ctime> 10 #include <list> 11 #include <set> 12 #include <map> 13 using namespace std; 14 typedef long long LL; 15 typedef pair <int, int> P; 16 struct trie { 17 int cnt; 18 trie *next[2]; 19 trie() { 20 cnt = 0; 21 for(int i = 0; i < 2; ++i) 22 next[i] = NULL; 23 } 24 }; 25 26 void insert(int num[], trie *root) { 27 trie *p = root; 28 for(int i = 30; i >= 0; --i) { 29 if(p->next[num[i]] == NULL) { 30 p->next[num[i]] = new trie(); 31 } 32 p = p->next[num[i]]; 33 p->cnt++; 34 } 35 } 36 37 void del(int num[], trie *root) { 38 trie *p = root; 39 for(int i = 30; i >= 0; --i) { 40 p = p->next[num[i]]; 41 p->cnt--; 42 } 43 } 44 45 int search(int num[], trie *root, int val) { 46 int res = 0; 47 trie *p = root; 48 for(int i = 30; i >= 0; --i) { 49 if(p->next[num[i]^1] != NULL && p->next[num[i]^1]->cnt > 0) { 50 p = p->next[num[i]^1]; 51 res += (1 << i); 52 } 53 else if(p->next[num[i]] != NULL && p->next[num[i]]->cnt > 0) { 54 p = p->next[num[i]]; 55 } 56 else { 57 res = 0; 58 break; 59 } 60 } 61 return max(val, res); 62 } 63 64 void destory(trie *root) { 65 if(root->next[0] != NULL) 66 destory(root->next[0]); 67 if(root->next[1] != NULL) 68 destory(root->next[1]); 69 delete(root); 70 } 71 72 int main() 73 { 74 trie *root = new trie(); 75 int n, val, num[40]; 76 char op[5]; 77 scanf("%d", &n); 78 while(n--) { 79 scanf("%s %d", op, &val); 80 int f = 0, temp = val; 81 do { 82 num[f++] = val % 2; 83 val /= 2; 84 }while(val); 85 while(f < 31) { 86 num[f++] = 0; 87 } 88 if(op[0] == '+') { 89 insert(num, root); 90 } 91 else if(op[0] == '-') { 92 del(num, root); 93 } 94 else { 95 printf("%d\n", root->next[0] != NULL || root->next[1] != NULL ? search(num, root, temp) : temp); 96 } 97 } 98 destory(root); 99 return 0; 100 }