Codeforces Round #367 Div2 D. Vasiliy's Multiset

問題

Problem - D - Codeforces

multiset に最初 0 が入っている。以下のような 3 種類のクエリが q 個くるので処理せよ。

  • x を 1 個 multiset に入れる。
  • x を 1 個 multiset から削除する。
  • multiset 内の各数字と x との xor をとった時の最大値を出力せよ。

解法

sugim48 先生のコードを参考にした。Trie 木を作り、追加と削除を Trie 木上で処理する。

x と Trie 木内の数字の xor の最大値を求めるとき、より上位のビットが 1 であるほど大きい数字になるので、上の方からビットを見ていって、1 にすることができるかどうかを確認していけば良い。制約から各クエリについて 30 ビット分見れば良いので間に合う。

コード

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.NoSuchElementException;

/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            pass System Test!
*/

public class D {
  private static class Task {
    class Trie {
      class Node {
        private int right, left, size;

        Node(int right, int left, int size) {
          this.right = right;
          this.left = left;
          this.size = size;
        }
      }

      ArrayList<Node> nodes = new ArrayList<>();

      Trie() {
        nodes.add(new Node(-1, -1, 0));
      }

      void add(int pos, int bit, int mask, int size) {
        nodes.get(pos).size += size;
        if (bit == -1) return;

        if ((mask & (1 << bit)) == 0) {
          // mask の bit ビット目が 0 の時、左の方に入れる

          // 左の子が空ならば、新しくノードを作る
          if (nodes.get(pos).left == -1) {
            nodes.add(new Node(-1, -1, 0));
            nodes.get(pos).left = nodes.size() - 1;
          }

          // 1 つ左側に潜る
          add(nodes.get(pos).left, bit - 1, mask, size);
        } else {
          // mask の bit ビット目が 0 の時、右の方に入れる

          // 右の子が空ならば、新しくノードを作る
          if (nodes.get(pos).right == -1) {
            nodes.add(new Node(-1, -1, 0));
            nodes.get(pos).right = nodes.size() - 1;
          }

          // 1 つ右側に潜る
          add(nodes.get(pos).right, bit - 1, mask, size);
        }
      }

      int getXorMax(int pos, int bit, int x, int ans) {
        if (bit == -1) return ans;
        if (((1 << bit) & x) == 0) {
          /*
            x の bit ビット目が 0 の時, Trie 木の中に bit ビット目が 1 のものがあれば, それとの Xor を取れば確実に大きい値が作れる。
            bit ビット目が 1 のものを求めて右側に潜ろうとする
           */

          if (nodes.get(pos).right != -1 && nodes.get(nodes.get(pos).right).size > 0) {
            /*
            右側に子がいれば潜る
             */
            ans |= (1 << bit);
            ans = getXorMax(nodes.get(pos).right, bit - 1, x, ans);
          } else {
            /*
            右側に子がいなければしかたがないので左に潜る
             */
            ans = getXorMax(nodes.get(pos).left, bit - 1, x, ans);
          }
        } else {
          /*
          x の bit ビット目が 1 の時, Trie 木の中に bit ビット目が 0 のものがあれば, それとの Xor を取れば確実に大きい値が作れる。
            bit ビット目が 0 のものを求めて左側に潜ろうとする
           */
          if (nodes.get(pos).left != -1 && nodes.get(nodes.get(pos).left).size > 0) {
            ans |= (1 << bit);
            ans = getXorMax(nodes.get(pos).left, bit - 1, x, ans);
          } else {
            ans = getXorMax(nodes.get(pos).right, bit - 1, x, ans);
          }
        }
        return ans;
      }
    }

    void solve(FastScanner in, PrintWriter out) {
      Trie trie = new Trie();
      trie.add(0, 30, 0, +1);

      int Q = in.nextInt();
      for (; Q > 0; Q--) {
        char c = in.next().toCharArray()[0];
        int x = in.nextInt();

        if (c == '+') trie.add(0, 30, x, +1);
        if (c == '-') trie.add(0, 30, x, -1);
        if (c == '?') out.println(trie.getXorMax(0, 30, x, 0));
      }
    }
  }

  /**
   * ここから下はテンプレートです。
   */
  public static void main(String[] args) {
    OutputStream outputStream = System.out;
    FastScanner in = new FastScanner();
    PrintWriter out = new PrintWriter(outputStream);
    Task solver = new Task();
    solver.solve(in, out);
    out.close();
  }
  private static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int bufferLength = 0;

    private boolean hasNextByte() {
      if (ptr < bufferLength) {
        return true;
      } else {
        ptr = 0;
        try {
          bufferLength = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (bufferLength <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) return buffer[ptr++];
      else return -1;
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

    boolean hasNext() {
      skipUnprintable();
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    long nextLong() {
      if (!hasNext()) throw new NoSuchElementException();
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    double nextDouble() {
      return Double.parseDouble(next());
    }

    double[] nextDoubleArray(int n) {
      double[] array = new double[n];
      for (int i = 0; i < n; i++) {
        array[i] = nextDouble();
      }
      return array;
    }

    double[][] nextDoubleMap(int n, int m) {
      double[][] map = new double[n][];
      for (int i = 0; i < n; i++) {
        map[i] = nextDoubleArray(m);
      }
      return map;
    }

    public int nextInt() {
      return (int) nextLong();
    }

    public int[] nextIntArray(int n) {
      int[] array = new int[n];
      for (int i = 0; i < n; i++) array[i] = nextInt();
      return array;
    }

    public long[] nextLongArray(int n) {
      long[] array = new long[n];
      for (int i = 0; i < n; i++) array[i] = nextLong();
      return array;
    }

    public String[] nextStringArray(int n) {
      String[] array = new String[n];
      for (int i = 0; i < n; i++) array[i] = next();
      return array;
    }

    public char[][] nextCharMap(int n) {
      char[][] array = new char[n][];
      for (int i = 0; i < n; i++) array[i] = next().toCharArray();
      return array;
    }
  }
}