cf706D

题目

http://codeforces.com/contest/706/problem/D

题解

Trie 模板

#include <bits/stdc++.h>

using namespace std;

#define rep(i, n) for (int i = 0; i < (int)(n); ++i)

const int BITS = 30;

int trie[8000010][2];
int sub[8000010];

int main() {
  int Q;
  scanf("%d", &Q);

  int n = 1;
  rep(i, 8000010) trie[i][0] = trie[i][1] = -1;

  int u = 0;
  sub[0]++;
  for (int j = BITS - 1; j >= 0; --j) {
    trie[u][0] = n++;
    u = trie[u][0];
    sub[u]++;
  }

  rep(_, Q) {
    char op;
    int x;
    scanf(" %c %d", &op, &x);

    if (op == '+') {
      int u = 0;
      sub[0]++;
      for (int j = BITS - 1; j >= 0; --j) {
        int b = (x >> j) & 1;
        if (trie[u][b] == -1) {
          trie[u][b] = n++;
        }
        u = trie[u][b];
        sub[u]++;
      }
    } else if (op == '-') {
      int u = 0;
      sub[0]--;
      for (int j = BITS - 1; j >= 0; --j) {
        int b = (x >> j) & 1;
        u = trie[u][b];
        sub[u]--;
      }
    } else {
      int res = 0;
      int u = 0;
      for (int j = BITS - 1; j >= 0; --j) {
        if (u == -1) break;
        int b = (x >> j) & 1;
        int v = trie[u][b ^ 1];
        if (v != -1 && sub[v] > 0) {
          u = v;
          res += 1 << j;
          continue;
        }
        u = trie[u][b];
      }

      printf("%d\n", res);
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/arg-53/p/9047449.html