ABC308G

· · 题解

本文中的集合均指可重集。

注意到异或有一个性质:

对于 x, y, z(x < y < z),\min\{x\ {\rm{xor}}\ y, y\ {\rm{xor}}\ z\}< x\ {\rm{xor}}\ z。

然后就很好做了。

根据这个性质,假如这个序列是排好序的,那么答案肯定是相邻两项 \rm xor 的最小值。

那我们用一个 std::multiset 来维护这些相邻两数的 \rm xor 值,然后答案在这个 std::multiset 里找就可以了。

维护一个候选数的 std::multiset。对于插入,每次在这个集合里找到和输入数相邻的两个数,把这两个插到答案集合里,然后再从答案集合里把原来的相邻两个数的 \rm xor 删掉;对于删除,我们把这个数和它相邻的数的 \rm xor 从答案里删掉,注意这里有两个,一个是它和比它小的,一个是比它大的,这个可以在候选集合中二分找到,然后再把那个比它小的和那个比它大的放到答案集合里。

显然,答案就是答案集合中最小的数,即 *answer.begin()。

代码:

#include<bits/stdc++.h>
using namespace std;

#define rep(i, l, r) for(auto i = (l); i <= (r); ++i)
#define per(i, r, l) for(auto i = (r); i >= (l); --i)

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  #define con1 it != candidate.end()
  #define con2 it != candidate.begin()
  multiset<int> candidate, answer;
  int m; cin >> m; while (m--) {
    int C2H5OH; cin >> C2H5OH; 
    if (C2H5OH == 1) {
      int pain; cin >> pain;
      auto it = candidate.lower_bound(pain);
      if (con1) {
        answer.insert((*it) ^ pain); 
      }
      if (con2) {
        auto it2 = it; --it2;
        answer.insert((*it2) ^ pain);
      }
      if (con1 && con2) {
        auto it2 = it; --it2;
        answer.erase(answer.find((*it) ^ (*it2)));
      }
      candidate.insert(pain);
    }

    if (C2H5OH == 2) {
      int pain; cin >> pain; 
      candidate.erase(candidate.find(pain));
      auto it = candidate.lower_bound(pain);
      if (con1) {
        answer.erase(answer.find((*it) ^ pain)); 
      }
      if (con2) {
        auto it2 = it; --it2;
        answer.erase(answer.find((*it2) ^ pain)); 
      }
      if (con1 && con2) {
        auto it2 = it; --it2;
        answer.insert((*it2) ^ (*it));
      }
    }

    if (C2H5OH == 3) {
      cerr << "> "; 
      cout << *answer.begin() << '\n';
    }
  }
  return ~~(0 ^ 0);
}