競技プログラミング用 C++ ライブラリ
test/set_xor_min.test.cpp · GitHub で見る
#define PROBLEM "https://judge.yosupo.jp/problem/set_xor_min"
#include "data_structure/xor_set.hpp"
#include "components/fast_io_bulk.hpp"
int main() {
FastInput input;
FastOutput output;
int q = 0;
input.read(q);
XorSet<> set;
read_unsigned_records<2>(input, q, [&](std::uint32_t type, std::uint32_t x) {
if (type == 0) set.insert(x);
else if (type == 1) set.erase(x);
else output.println(set.min_xor(x));
});
}
#line 1 "test/set_xor_min.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/set_xor_min"
#line 1 "data_structure/xor_set.hpp"
#line 1 "components/predecessor_set.hpp"
#line 1 "components/xor_select.hpp"
#include <bit>
#include <cassert>
#include <cstdint>
namespace xor_select_detail {
inline unsigned argmin(std::uint64_t word, unsigned key) {
assert(word && key < 64);
if (std::has_single_bit(word)) return std::countr_zero(word);
if ((word >> key) & 1) return key;
unsigned shift = key & 32;
word = std::rotl(word, shift);
auto exchange = [&](unsigned shift, std::uint64_t mask) {
word = ((word & mask) << shift) | ((word & ~mask) >> shift);
};
exchange(key & 16, 0x0000ffff0000ffffULL);
exchange(key & 8, 0x00ff00ff00ff00ffULL);
exchange(key & 4, 0x0f0f0f0f0f0f0f0fULL);
exchange(key & 2, 0x3333333333333333ULL);
exchange(key & 1, 0x5555555555555555ULL);
return std::countr_zero(word) ^ key;
}
}
#line 5 "components/predecessor_set.hpp"
#include <algorithm>
#include <array>
#line 9 "components/predecessor_set.hpp"
#include <cstddef>
#line 11 "components/predecessor_set.hpp"
#include <cstring>
#include <limits>
#include <span>
#include <string_view>
#include <utility>
#include <vector>
#if defined(__x86_64__) && (defined(__GNUC__) || defined(__clang__))
#include <immintrin.h>
#endif
namespace predecessor_set_detail {
inline void pack_scalar(const char *src, std::uint64_t *dst, std::size_t words) {
for (std::size_t i = 0; i < words; ++i) {
std::uint64_t word = 0;
if constexpr (std::endian::native == std::endian::little) {
for (int j = 0; j < 8; ++j) {
std::uint64_t x;
std::memcpy(&x, src + i * 64 + j * 8, 8);
assert((x & 0xfefefefefefefefeULL) == 0x3030303030303030ULL);
word |= ((x & 0x0101010101010101ULL) * 0x0102040810204080ULL >> 56) << (j * 8);
}
} else {
for (int j = 0; j < 64; ++j) {
assert(src[i * 64 + j] == '0' || src[i * 64 + j] == '1');
word |= std::uint64_t(src[i * 64 + j] - '0') << j;
}
}
dst[i] = word;
}
}
#if defined(__x86_64__) && (defined(__GNUC__) || defined(__clang__))
__attribute__((target("avx2"))) inline void pack_avx2(const char *src, std::uint64_t *dst, std::size_t words) {
const auto ones = _mm256_set1_epi8('1');
for (std::size_t i = 0; i < words; ++i) {
auto a = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(src + i * 64));
auto b = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(src + i * 64 + 32));
assert(_mm256_movemask_epi8(_mm256_cmpeq_epi8(_mm256_and_si256(a, _mm256_set1_epi8(-2)), _mm256_set1_epi8('0'))) == -1);
assert(_mm256_movemask_epi8(_mm256_cmpeq_epi8(_mm256_and_si256(b, _mm256_set1_epi8(-2)), _mm256_set1_epi8('0'))) == -1);
auto low = std::uint32_t(_mm256_movemask_epi8(_mm256_cmpeq_epi8(a, ones)));
auto high = std::uint32_t(_mm256_movemask_epi8(_mm256_cmpeq_epi8(b, ones)));
dst[i] = low | (std::uint64_t(high) << 32);
}
}
#endif
inline void pack(const char *src, std::uint64_t *dst, std::size_t words) {
#if defined(__x86_64__) && (defined(__GNUC__) || defined(__clang__))
if (words >= 4 && __builtin_cpu_supports("avx2")) return pack_avx2(src, dst, words);
#endif
pack_scalar(src, dst, words);
}
}
class PredecessorSet {
int n = 0, count = 0, height = 0;
std::array<int, 6> offset{}, length{};
std::array<int, 16> small{};
bool small_valid = false;
std::vector<std::uint64_t> data;
void mask_tail() {
int bits = n;
for (int h = 0; h < height; ++h) {
if (bits & 63) data[offset[h] + length[h] - 1] &= ~std::uint64_t(0) >> (64 - (bits & 63));
bits = length[h];
}
}
void rebuild() {
count = 0;
for (int i = 0; i < length[0]; ++i) count += std::popcount(data[i]);
for (int h = 1; h < height; ++h)
for (int i = 0; i < length[h - 1]; ++i)
if (data[offset[h - 1] + i]) data[offset[h] + (i >> 6)] |= std::uint64_t(1) << (i & 63);
rebuild_small();
}
template <int H, bool Forward> int descend(int p) const {
if constexpr (H == 0) return p;
else {
auto word = data[offset[H - 1] + p];
int bit = Forward ? std::countr_zero(word) : 63 - std::countl_zero(word);
return descend<H - 1, Forward>(p * 64 + bit);
}
}
template <int H, bool Forward> int ascend(int p) const {
if constexpr (H == 6) return Forward ? n : -1;
else {
if (H >= height) return Forward ? n : -1;
auto word = data[offset[H] + (p >> 6)];
auto mask = Forward ? (~std::uint64_t(1) << (p & 63)) : ~(~std::uint64_t(0) << (p & 63));
word &= mask;
if (word) {
int bit = Forward ? std::countr_zero(word) : 63 - std::countl_zero(word);
return descend<H, Forward>((p & ~63) + bit);
}
return ascend<H + 1, Forward>(p >> 6);
}
}
void rebuild_small() {
small_valid = count <= int(small.size());
if (!small_valid) return;
small.fill(n);
for (int i = 0, p = 0; i < count; ++i) {
auto word = data[p >> 6] >> (p & 63);
p = word ? p + std::countr_zero(word) : ascend<1, true>(p >> 6);
small[i] = p++;
}
}
int small_rank(int p) const {
#if defined(__AVX512F__) && defined(__x86_64__)
auto keys = _mm512_loadu_si512(small.data());
return std::popcount(unsigned(_mm512_cmp_epi32_mask(keys, _mm512_set1_epi32(p), _MM_CMPINT_LT)));
#elif defined(__AVX2__) && defined(__x86_64__)
auto key = _mm256_set1_epi32(p);
auto a = _mm256_cmpgt_epi32(key, _mm256_loadu_si256(reinterpret_cast<const __m256i *>(small.data())));
auto b = _mm256_cmpgt_epi32(key, _mm256_loadu_si256(reinterpret_cast<const __m256i *>(small.data() + 8)));
return std::popcount(unsigned(_mm256_movemask_ps(_mm256_castsi256_ps(a)))) + std::popcount(unsigned(_mm256_movemask_ps(_mm256_castsi256_ps(b))));
#else
int result = 0;
for (int x : small) result += x < p;
return result;
#endif
}
public:
int argmin_xor(std::uint32_t x) const {
if (!count) return -1;
std::uint64_t p = std::uint64_t(x) & ((std::uint64_t(1) << (height * 6)) - 1);
for (int h = 0; h < height; ++h, p >>= 6) {
auto index = p >> 6;
if (index >= unsigned(length[h])) continue;
auto word = data[offset[h] + index];
if (!word) continue;
p = index * 64 + xor_select_detail::argmin(word, p & 63);
while (h--) p = p * 64 + xor_select_detail::argmin(data[offset[h] + p], (x >> (h * 6)) & 63);
return int(p);
}
return -1;
}
int argmax_xor(std::uint32_t x) const { return argmin_xor(~x); }
explicit PredecessorSet(int n = 0, bool filled = false) { assign(n, filled); }
explicit PredecessorSet(std::string_view bits) { assign(bits); }
PredecessorSet(int n, std::span<const std::uint64_t> words) { assign(n, words); }
PredecessorSet(const PredecessorSet &) = default;
PredecessorSet &operator=(const PredecessorSet &) = default;
PredecessorSet(PredecessorSet &&other) noexcept : PredecessorSet() { swap(other); }
PredecessorSet &operator=(PredecessorSet &&other) noexcept {
if (this != &other) { PredecessorSet moved(std::move(other)); swap(moved); }
return *this;
}
void assign(int length, bool filled = false) {
assert(length >= 0);
n = length; count = filled ? n : 0; height = 0;
offset.fill(0); this->length.fill(0);
int total = 0;
for (std::size_t bits = n; bits;) {
std::size_t words = (bits + 63) / 64;
offset[height] = total; this->length[height++] = words;
total += words;
if (words == 1) break;
bits = words;
}
data.assign(total, filled ? ~std::uint64_t(0) : 0);
if (filled) mask_tail();
rebuild_small();
}
void assign(std::string_view bits) {
assert(bits.size() <= std::size_t(std::numeric_limits<int>::max()));
PredecessorSet next(static_cast<int>(bits.size()));
std::size_t words = bits.size() / 64;
predecessor_set_detail::pack(bits.data(), next.data.data(), words);
for (std::size_t i = words * 64; i < bits.size(); ++i) {
assert(bits[i] == '0' || bits[i] == '1');
next.data[i >> 6] |= std::uint64_t(bits[i] - '0') << (i & 63);
}
next.rebuild(); swap(next);
}
void assign(int n, std::span<const std::uint64_t> words) {
assert(n >= 0 && words.size() == (std::size_t(n) + 63) / 64);
PredecessorSet next(n);
std::copy(words.begin(), words.end(), next.data.begin());
if (n & 63) next.data[next.length[0] - 1] &= ~std::uint64_t(0) >> (64 - (n & 63));
next.rebuild(); swap(next);
}
int universe_size() const { return n; }
int size() const { return count; }
bool empty() const { return count == 0; }
bool contains(int p) const { assert(0 <= p && p < n); return data[p >> 6] >> (p & 63) & 1; }
bool insert(int p) {
assert(0 <= p && p < n);
int index = p >> 6;
auto &leaf = data[index];
auto mask = std::uint64_t(1) << (p & 63), before = leaf;
leaf = before | mask;
bool changed = !(before & mask);
count += changed;
if (!before) for (int h = 1; h < height; ++h) {
auto &word = data[offset[h] + (index >> 6)];
auto old = word;
word |= std::uint64_t(1) << (index & 63);
if (old) break;
index >>= 6;
}
small_valid = false;
return changed;
}
bool erase(int p) {
assert(0 <= p && p < n);
int index = p >> 6;
auto &leaf = data[index];
auto mask = std::uint64_t(1) << (p & 63), before = leaf;
leaf = before & ~mask;
bool changed = (before & mask) != 0;
count -= changed;
if (before && !leaf) for (int h = 1; h < height; ++h) {
auto &word = data[offset[h] + (index >> 6)];
word &= ~(std::uint64_t(1) << (index & 63));
if (word) break;
index >>= 6;
}
small_valid = false;
return changed;
}
int next(int p) const {
p = std::max(p, 0);
if (p >= n || !count) return n;
if (small_valid) {
int index = small_rank(p);
return index == count ? n : small[index];
}
auto local = data[p >> 6] >> (p & 63);
if (local) return p + std::countr_zero(local);
return ascend<1, true>(p >> 6);
}
int prev(int p) const {
p = std::min(p, n - 1);
if (p < 0 || !count) return -1;
if (small_valid) {
int index = small_rank(p + 1);
return index ? small[index - 1] : -1;
}
auto local = data[p >> 6] << (63 - (p & 63));
if (local) return p - std::countl_zero(local);
return ascend<1, false>(p >> 6);
}
bool set(int p, bool present) {
assert(0 <= p && p < n);
int index = p >> 6;
auto &leaf = data[index];
auto mask = std::uint64_t(1) << (p & 63), before = leaf;
auto fill = std::uint64_t(0) - present;
leaf = before ^ ((before ^ fill) & mask);
bool old = (before & mask) != 0;
count += int(present) - int(old);
if ((!before) != (!leaf)) for (int h = 1; h < height; ++h) {
auto &word = data[offset[h] + (index >> 6)];
auto previous = word;
word = previous ^ ((previous ^ fill) & (std::uint64_t(1) << (index & 63)));
if ((!previous) == (!word)) break;
index >>= 6;
}
small_valid = false;
return old != present;
}
int min() const { return next(0); }
int max() const { return prev(n - 1); }
void clear() { std::fill(data.begin(), data.end(), 0); count = 0; small_valid = false; }
void fill() {
std::fill(data.begin(), data.end(), ~std::uint64_t(0));
mask_tail();
count = n;
rebuild_small();
}
template <class F> void for_each(int l, int r, F &&f) const {
assert(0 <= l && l <= r && r <= n);
for (int p = next(l); p < r;) {
int base = p & ~63;
auto word = data[p >> 6] & (~std::uint64_t(0) << (p & 63));
if (r - base < 64) word &= ~std::uint64_t(0) >> (64 - (r - base));
while (word) { f(base + std::countr_zero(word)); word &= word - 1; }
if (r - base <= 64) break;
p = next(base + 64);
}
}
template <class F> void for_each(F &&f) const { for_each(0, n, f); }
std::vector<int> to_vector() const {
std::vector<int> out; out.reserve(count);
for_each([&](int x) { out.push_back(x); }); return out;
}
std::span<const std::uint64_t> words() const & { return {data.data(), std::size_t(length[0])}; }
void words() const && = delete;
void swap(PredecessorSet &other) noexcept {
using std::swap;
swap(n, other.n); swap(count, other.count); swap(height, other.height);
offset.swap(other.offset); length.swap(other.length); data.swap(other.data); small.swap(other.small); swap(small_valid, other.small_valid);
}
std::size_t memory_usage() const { return data.capacity() * sizeof(std::uint64_t); }
};
#line 13 "data_structure/xor_set.hpp"
template <int Bits = 30>
class XorSet {
static_assert(1 <= Bits && Bits <= 31);
static constexpr int leaf_bits = std::min(Bits, 9);
static constexpr std::uint32_t leaf_mask = (std::uint32_t(1) << leaf_bits) - 1;
static constexpr std::uint32_t block_count = std::uint32_t(1) << (Bits - leaf_bits);
static constexpr std::uint32_t singleton = std::uint32_t(1) << 31;
struct alignas(64) Leaf {
std::array<std::uint64_t, 8> words{};
};
std::vector<std::uint32_t> directory;
PredecessorSet occupied;
std::vector<Leaf> leaves;
std::uint32_t free_leaf = 0, all_xor = 0;
std::int64_t count = 0;
void ensure_storage() {
if (!directory.empty()) return;
std::vector<std::uint32_t> next(block_count);
PredecessorSet index(block_count);
directory.swap(next);
occupied.swap(index);
}
std::uint32_t make_leaf() {
if (free_leaf) {
auto id = free_leaf;
free_leaf = std::uint32_t(leaves[id].words[0]);
leaves[id] = Leaf{};
return id;
}
if (leaves.empty()) leaves.emplace_back();
leaves.emplace_back();
return std::uint32_t(leaves.size() - 1);
}
void release_leaf(std::uint32_t id) {
leaves[id].words[0] = free_leaf;
free_leaf = id;
}
static void check([[maybe_unused]] std::uint32_t value) { assert(value < (std::uint32_t(1) << Bits)); }
public:
using value_type = std::uint32_t;
XorSet() = default;
XorSet(const XorSet &) = default;
XorSet &operator=(const XorSet &other) {
if (this != &other) { XorSet copy(other); swap(copy); }
return *this;
}
XorSet(XorSet &&other) noexcept
: directory(std::move(other.directory)), occupied(std::move(other.occupied)), leaves(std::move(other.leaves)),
free_leaf(std::exchange(other.free_leaf, 0)), all_xor(std::exchange(other.all_xor, 0)), count(std::exchange(other.count, 0)) {
other.directory.clear(); other.leaves.clear();
}
XorSet &operator=(XorSet &&other) noexcept {
if (this != &other) { XorSet moved(std::move(other)); swap(moved); }
return *this;
}
std::int64_t size() const { return count; }
bool empty() const { return count == 0; }
bool contains(std::uint32_t value) const {
check(value);
if (empty()) return false;
auto entry = directory[value >> leaf_bits];
if (!entry) return false;
if (entry & singleton) return entry == (singleton | (value & leaf_mask));
return leaves[entry].words[(value & leaf_mask) >> 6] >> (value & 63) & 1;
}
bool insert(std::uint32_t value) {
check(value);
ensure_storage();
auto &entry = directory[value >> leaf_bits];
auto suffix = value & leaf_mask;
if (!entry) {
occupied.insert(value >> leaf_bits);
entry = singleton | suffix;
} else if (entry & singleton) {
auto old = entry ^ singleton;
if (old == suffix) return false;
auto id = make_leaf();
leaves[id].words[old >> 6] = std::uint64_t(1) << (old & 63);
leaves[id].words[suffix >> 6] |= std::uint64_t(1) << (suffix & 63);
entry = id;
} else {
auto &word = leaves[entry].words[suffix >> 6];
auto bit = std::uint64_t(1) << (suffix & 63);
if (word & bit) return false;
word |= bit;
}
++count; all_xor ^= value;
return true;
}
bool erase(std::uint32_t value) {
check(value);
if (empty()) return false;
auto &entry = directory[value >> leaf_bits];
if (!entry) return false;
if (entry & singleton) {
if (entry != (singleton | (value & leaf_mask))) return false;
entry = 0;
occupied.erase(value >> leaf_bits);
} else {
auto &leaf = leaves[entry];
auto &word = leaf.words[(value & leaf_mask) >> 6];
auto bit = std::uint64_t(1) << (value & 63);
if (!(word & bit)) return false;
word ^= bit;
std::uint64_t any = 0;
for (auto part : leaf.words) any |= part;
if (!any) {
release_leaf(entry);
entry = 0;
occupied.erase(value >> leaf_bits);
}
}
--count; all_xor ^= value;
return true;
}
std::uint32_t argmin_xor(std::uint32_t value) const {
assert(!empty());
if (count == 1) return all_xor;
auto prefix = (value >> leaf_bits) & (block_count - 1);
if (!directory[prefix]) prefix = occupied.argmin_xor(value >> leaf_bits);
auto entry = directory[prefix];
if (entry & singleton) return (prefix << leaf_bits) | (entry ^ singleton);
const auto &leaf = leaves[entry];
auto preferred = (value & leaf_mask) >> 6;
for (unsigned distance = 0; distance < 8; ++distance) {
auto i = preferred ^ distance;
if (leaf.words[i]) return (prefix << leaf_bits) | (i << 6) | xor_select_detail::argmin(leaf.words[i], value & 63);
}
std::unreachable();
}
std::uint32_t argmax_xor(std::uint32_t value) const { return argmin_xor(~value); }
std::uint32_t min_xor(std::uint32_t value) const { return argmin_xor(value) ^ value; }
std::uint32_t max_xor(std::uint32_t value) const { return argmax_xor(value) ^ value; }
void clear() {
std::fill(directory.begin(), directory.end(), 0);
occupied.clear(); leaves.clear();
free_leaf = all_xor = 0; count = 0;
}
void swap(XorSet &other) noexcept {
directory.swap(other.directory); occupied.swap(other.occupied); leaves.swap(other.leaves);
std::swap(free_leaf, other.free_leaf); std::swap(all_xor, other.all_xor); std::swap(count, other.count);
}
std::size_t memory_usage() const { return directory.capacity() * sizeof(std::uint32_t) + occupied.memory_usage() + leaves.capacity() * sizeof(Leaf); }
};
#line 1 "components/fast_io_bulk.hpp"
#line 1 "components/fast_io_output.hpp"
#line 1 "components/fast_io.hpp"
#line 8 "components/fast_io.hpp"
#include <charconv>
#line 11 "components/fast_io.hpp"
#include <cstdio>
#line 13 "components/fast_io.hpp"
#include <memory>
#include <stdexcept>
#include <string>
#line 17 "components/fast_io.hpp"
#include <type_traits>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace fast_io_detail { struct BulkInput; struct BulkOutput; }
class FastInput {
friend struct fast_io_detail::BulkInput;
static constexpr std::size_t capacity = 1 << 16;
FILE *file = nullptr;
std::unique_ptr<char[]> buffer;
const char *current = "", *end = current;
std::string scratch;
void *mapping = nullptr;
std::size_t mapped_size = 0;
bool refill() {
if (!file) return false;
std::size_t n = std::fread(buffer.get(), 1, capacity, file);
current = buffer.get();
end = current + n;
return n;
}
static const char *scan(const char *p, const char *end) {
while (end - p >= 8) {
std::uint64_t x;
std::memcpy(&x, p, 8);
if ((x - 0x2121212121212121ULL) & ~x & 0x8080808080808080ULL) break;
p += 8;
}
while (p != end && static_cast<unsigned char>(*p) > ' ') ++p;
return p;
}
public:
explicit FastInput(FILE *input = stdin) {
#if defined(__unix__) || defined(__APPLE__)
struct stat status;
int fd = fileno(input);
auto offset = ftello(input);
if (fd >= 0 && offset >= 0 && !fstat(fd, &status) && S_ISREG(status.st_mode) && status.st_size > offset) {
mapped_size = status.st_size;
mapping = mmap(nullptr, mapped_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapping != MAP_FAILED) {
current = static_cast<const char *>(mapping) + offset;
end = static_cast<const char *>(mapping) + mapped_size;
return;
}
mapping = nullptr;
}
#endif
file = input;
buffer = std::make_unique_for_overwrite<char[]>(capacity);
}
explicit FastInput(std::string_view input) : current(input.empty() ? "" : input.data()), end(current + input.size()) {}
FastInput(const FastInput &) = delete;
FastInput &operator=(const FastInput &) = delete;
~FastInput() {
#if defined(__unix__) || defined(__APPLE__)
if (mapping) munmap(mapping, mapped_size);
#endif
}
std::string_view token() {
while (true) {
while (current != end && static_cast<unsigned char>(*current) <= ' ') ++current;
if (current != end) break;
if (!refill()) return {};
}
const char *begin = current;
current = scan(current, end);
if (current != end || !file) return {begin, std::size_t(current - begin)};
scratch.assign(begin, end);
while (refill()) {
current = scan(current, end);
scratch.append(buffer.get(), std::size_t(current - buffer.get()));
if (current != end) break;
}
return scratch;
}
template <class T>
bool read(T &value) {
if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
while (true) {
while (current != end && static_cast<unsigned char>(*current) <= ' ') ++current;
if (current != end) break;
if (!refill()) return false;
}
if constexpr (std::is_unsigned_v<T> && sizeof(T) == 4 && std::endian::native == std::endian::little) {
if (end - current >= 11) {
std::uint64_t x;
std::memcpy(&x, current, 8);
if (!(((x + 0x4646464646464646ULL) | (x - 0x3030303030303030ULL)) & 0x8080808080808080ULL)) {
x &= 0x0f0f0f0f0f0f0f0fULL;
x = (x * 10 + (x >> 8)) & 0x00ff00ff00ff00ffULL;
x = (x * 100 + (x >> 16)) & 0x0000ffff0000ffffULL;
std::uint64_t v = std::uint32_t(x * 10000 + (x >> 32));
int n = 8;
for (; n < 10 && static_cast<unsigned char>(current[n]) - unsigned('0') < 10; ++n)
v = v * 10 + (current[n] - '0');
if (static_cast<unsigned char>(current[n]) <= ' ' && v <= 0xffffffffULL) {
current += n;
value = T(v);
return true;
}
}
}
}
T parsed{};
auto result = std::from_chars(current, end, parsed);
if (result.ec == std::errc{} && (result.ptr != end ? static_cast<unsigned char>(*result.ptr) <= ' ' : !file)) {
current = result.ptr;
value = parsed;
return true;
}
}
auto s = token();
if (s.empty()) return false;
if constexpr (std::is_same_v<T, bool>) {
assert(s == "0" || s == "1");
value = s[0] == '1';
} else if constexpr (std::is_integral_v<T>) {
auto result = std::from_chars(s.data(), s.data() + s.size(), value);
assert(result.ec == std::errc{} && result.ptr == s.data() + s.size());
(void)result;
} else value = T(s);
return true;
}
};
class FastOutput {
friend struct fast_io_detail::BulkOutput;
inline static constexpr auto quads = [] {
std::array<std::array<char, 4>, 10000> table{};
for (int i = 0; i < 10000; ++i)
table[i] = {char('0' + i / 1000), char('0' + i / 100 % 10), char('0' + i / 10 % 10), char('0' + i % 10)};
return table;
}();
FILE *file;
std::unique_ptr<char[]> buffer = std::make_unique_for_overwrite<char[]>(1 << 16);
std::size_t capacity = 1 << 16, length = 0;
char *reserve(std::size_t n) {
if (n > capacity - length) {
if (!flush()) throw std::runtime_error("output failed");
if (n > capacity) {
std::size_t next = std::max(n, 2 * capacity);
buffer = std::make_unique_for_overwrite<char[]>(next);
capacity = next;
}
}
return buffer.get() + length;
}
public:
explicit FastOutput(FILE *output = stdout) : file(output) {}
FastOutput(const FastOutput &) = delete;
FastOutput &operator=(const FastOutput &) = delete;
~FastOutput() { flush(); }
bool flush() {
std::size_t offset = 0;
while (offset < length) {
auto n = std::fwrite(buffer.get() + offset, 1, length - offset, file);
if (!n) {
std::memmove(buffer.get(), buffer.get() + offset, length - offset);
length -= offset;
return false;
}
offset += n;
}
length = 0;
return std::fflush(file) == 0;
}
void write(char c) { *reserve(1) = c; ++length; }
void write(__uint128_t value) {
char digits[40];
char *end = digits + sizeof(digits), *begin = end;
do { *--begin = char('0' + value % 10); value /= 10; } while (value);
write(std::string_view(begin, end - begin));
}
void write(__int128_t value) {
__uint128_t magnitude = __uint128_t(value);
if (value < 0) write('-'), magnitude = 0 - magnitude;
write(magnitude);
}
void write(std::string_view s) {
char *out = reserve(s.size());
if (!s.empty()) std::memcpy(out, s.data(), s.size());
length += s.size();
}
template <class T> requires std::is_integral_v<T>
void write(T value) {
char *out = reserve(32);
if constexpr (std::is_same_v<T, bool>) *out = '0' + value, ++length;
else if constexpr (std::is_unsigned_v<T> && sizeof(T) == 4) {
char *p = out;
if (value >= 100000000) {
auto high = value / 100000000, low = value % 100000000;
p = std::to_chars(p, p + 2, high).ptr;
std::memcpy(p, quads[low / 10000].data(), 4);
std::memcpy(p + 4, quads[low % 10000].data(), 4);
p += 8;
} else if (value >= 10000) {
p = std::to_chars(p, p + 4, value / 10000).ptr;
std::memcpy(p, quads[value % 10000].data(), 4);
p += 4;
} else p = std::to_chars(p, p + 4, value).ptr;
length += p - out;
} else length += std::to_chars(out, out + 32, value).ptr - out;
}
template <class T> requires requires(const T &value, char *out) { value.decimal_capacity(); value.to_chars(out); }
void write(const T &value) {
char *out = reserve(value.decimal_capacity());
length += value.to_chars(out) - out;
}
template <class T>
void println(const T &value) { write(value); write('\n'); }
};
#line 7 "components/fast_io_output.hpp"
namespace fast_io_detail {
struct BulkOutput {
static char *small(char *out, std::uint32_t value) {
unsigned n = 1 + (value >= 10) + (value >= 100) + (value >= 1000);
if constexpr (std::endian::native == std::endian::little) {
std::uint32_t word;
std::memcpy(&word, FastOutput::quads[value].data(), 4);
word >>= (4 - n) * 8;
std::memcpy(out, &word, 4);
} else std::memcpy(out, FastOutput::quads[value].data() + 4 - n, n);
return out + n;
}
static char *number(char *out, std::uint32_t value) {
if (value >= 100000000) {
out = small(out, value / 100000000);
value %= 100000000;
std::memcpy(out, FastOutput::quads[value / 10000].data(), 4);
std::memcpy(out + 4, FastOutput::quads[value % 10000].data(), 4);
return out + 8;
}
if (value >= 10000) {
out = small(out, value / 10000);
std::memcpy(out, FastOutput::quads[value % 10000].data(), 4);
return out + 4;
}
return small(out, value);
}
template<std::size_t Fields, class Read>
#if defined(__GNUC__) || defined(__clang__)
[[gnu::noinline]]
#endif
static void records(FastOutput &out, std::size_t count, Read read) {
constexpr auto bytes = 11 * Fields;
constexpr auto block = std::max<std::size_t>(1, (1 << 16) / bytes);
for (std::size_t base = 0; base < count;) {
const auto n = std::min(count - base, block);
char *begin = out.reserve(n * bytes), *p = begin;
for (std::size_t i = 0; i < n; ++i) {
auto values = read(base + i);
for (std::size_t j = 0; j < Fields; ++j) {
p = number(p, std::uint32_t(values[j]));
*p++ = j + 1 == Fields ? '\n' : ' ';
}
}
out.length += p - begin;
base += n;
}
}
static void write(FastOutput &out, std::string_view text) {
if (text.size() <= (1 << 16)) return out.write(text);
if (out.length && !out.flush()) throw std::runtime_error("output failed");
std::size_t done = 0;
while (done < text.size()) {
const auto written = std::fwrite(text.data() + done, 1, text.size() - done, out.file);
if (!written) throw std::runtime_error("output failed");
done += written;
}
}
};
}
template<std::size_t Fields, class Read>
void write_unsigned_records(FastOutput &output, std::size_t count, Read read) {
static_assert(Fields > 0 && Fields <= std::numeric_limits<std::size_t>::max() / 11);
fast_io_detail::BulkOutput::records<Fields>(output, count, std::move(read));
}
#line 8 "components/fast_io_bulk.hpp"
#if defined(__linux__) && defined(__x86_64__) && defined(__GNUC__) && !defined(__clang__)
#include <immintrin.h>
#pragma GCC push_options
_Pragma("GCC target(\"avx2\")")
#pragma GCC optimize("O3")
namespace fast_io_detail {
struct BulkInput {
alignas(32) static inline constexpr auto rows = [] {
std::array<std::array<unsigned char, 16>, 11> r{};
for (int n = 0; n <= 10; ++n)
for (int i = 0; i < 16; ++i) r[n][i] = i < 16 - n ? 128 : i - (16 - n);
return r;
}();
static constexpr std::size_t kChunk = 1 << 17, kCapacity = kChunk / 4 + 66;
static unsigned separators(__m256i bytes) {
return unsigned(_mm256_movemask_epi8(_mm256_cmpeq_epi8(_mm256_max_epu8(bytes, _mm256_set1_epi8(' ')), _mm256_set1_epi8(' '))));
}
[[gnu::always_inline]] static __m256i two(const char *&p, __m256i &invalid) {
const auto bytes = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(p));
const unsigned sep = separators(bytes), a = std::countr_zero(sep), b = std::countr_zero(sep & (sep - 1));
if (a < 1 || a > 10 || b <= a + 1 || b - a - 1 > 10) [[unlikely]] {
invalid = _mm256_set1_epi32(-1);
p += std::min(b + 1, 32u);
return _mm256_setzero_si256();
}
const auto window = _mm256_inserti128_si256(bytes, _mm_loadu_si128(reinterpret_cast<const __m128i *>(p + a + 1)), 1);
const auto control = _mm256_set_m128i(_mm_loadu_si128(reinterpret_cast<const __m128i *>(rows[b - a - 1].data())),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(rows[a].data())));
const auto digits = _mm256_shuffle_epi8(_mm256_sub_epi8(window, _mm256_set1_epi8('0')), control);
invalid = _mm256_or_si256(invalid, _mm256_subs_epu8(digits, _mm256_set1_epi8(9)));
p += b + 1;
return _mm256_madd_epi16(_mm256_maddubs_epi16(digits, _mm256_set1_epi16(0x010a)), _mm256_set1_epi32(0x00010064));
}
static std::uint32_t one(const char *&p, bool &bad) {
const auto bytes = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p));
const auto spaces = _mm_cmpeq_epi8(_mm_max_epu8(bytes, _mm_set1_epi8(' ')), _mm_set1_epi8(' '));
const unsigned n = std::countr_zero(unsigned(_mm_movemask_epi8(spaces)) | 0x10000u);
if (n < 1 || n > 10) [[unlikely]] {
bad = true;
p += std::min(n + 1, 16u);
return 0;
}
const auto digits = _mm_shuffle_epi8(_mm_sub_epi8(bytes, _mm_set1_epi8('0')),
_mm_loadu_si128(reinterpret_cast<const __m128i *>(rows[n].data())));
const auto invalid = _mm_subs_epu8(digits, _mm_set1_epi8(9));
bad |= !_mm_testz_si128(invalid, invalid);
const auto groups = _mm_madd_epi16(_mm_maddubs_epi16(digits, _mm_set1_epi16(0x010a)), _mm_set1_epi32(0x00010064));
const auto halves = _mm_madd_epi16(_mm_packus_epi32(groups, groups), _mm_set1_epi32(0x00012710));
const std::uint64_t value = std::uint64_t(unsigned(_mm_cvtsi128_si32(halves))) * 100000000 + unsigned(_mm_extract_epi32(halves, 1));
bad |= value > 0xffffffffULL;
p += n + 1;
return std::uint32_t(value);
}
static const char *after_separator(const char *p) {
const unsigned mask = separators(_mm256_loadu_si256(reinterpret_cast<const __m256i *>(p)));
return mask ? p + std::countr_zero(mask) + 1 : nullptr;
}
static std::size_t lockstep(const char *(&streams)[4], const char *const (&end)[4], unsigned *const (&out)[4], __m256i &invalid) {
const char *p[4] = {streams[0], streams[1], streams[2], streams[3]};
std::size_t done = 0;
for (;;) {
std::ptrdiff_t left = end[0] - p[0];
for (int k = 1; k < 4; ++k) left = std::min(left, end[k] - p[k]);
const auto steps = std::min(left / 33, std::ptrdiff_t((kCapacity - done) / 2));
if (steps <= 0) break;
for (auto j = steps; j; --j, done += 2) {
const auto g0 = two(p[0], invalid), g1 = two(p[1], invalid), g2 = two(p[2], invalid), g3 = two(p[3], invalid);
const auto k = _mm256_set1_epi32(0x00012710);
const auto h01 = _mm256_castsi256_ps(_mm256_madd_epi16(_mm256_packus_epi32(g0, g1), k));
const auto h23 = _mm256_castsi256_ps(_mm256_madd_epi16(_mm256_packus_epi32(g2, g3), k));
const auto high = _mm256_castps_si256(_mm256_shuffle_ps(h01, h23, 0x88));
const auto low = _mm256_castps_si256(_mm256_shuffle_ps(h01, h23, 0xdd));
const auto overflow = _mm256_or_si256(_mm256_cmpgt_epi32(high, _mm256_set1_epi32(42)),
_mm256_and_si256(_mm256_cmpeq_epi32(high, _mm256_set1_epi32(42)), _mm256_cmpgt_epi32(low, _mm256_set1_epi32(94967295))));
invalid = _mm256_or_si256(invalid, overflow);
const auto value = _mm256_add_epi32(_mm256_mullo_epi32(high, _mm256_set1_epi32(100000000)), low);
const auto q = _mm256_permutevar8x32_epi32(value, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
const auto q01 = _mm256_castsi256_si128(q), q23 = _mm256_extracti128_si256(q, 1);
_mm_storel_epi64(reinterpret_cast<__m128i *>(out[0] + done), q01);
_mm_storeh_pd(reinterpret_cast<double *>(out[1] + done), _mm_castsi128_pd(q01));
_mm_storel_epi64(reinterpret_cast<__m128i *>(out[2] + done), q23);
_mm_storeh_pd(reinterpret_cast<double *>(out[3] + done), _mm_castsi128_pd(q23));
}
}
for (int k = 0; k < 4; ++k) streams[k] = p[k];
return done;
}
template <class Emit>
static std::size_t chunk_blocks(const char *&p, const char *limit, std::size_t count, unsigned *const (&out)[4], Emit &&emit) {
const auto bytes = std::min({kChunk, 2 * (count - 32), std::size_t(limit - p) - 64}) & ~std::size_t(3);
const std::size_t stream = bytes / 4;
const char *p1 = after_separator(p + stream), *p2 = after_separator(p + 2 * stream);
const char *p3 = after_separator(p + 3 * stream), *last = after_separator(p + bytes);
if (!p1 || !p2 || !p3 || !last) return 0;
const char *s[4] = {p, p1, p2, p3}, *const end[4] = {p1, p2, p3, last};
auto invalid = _mm256_setzero_si256();
const auto done = lockstep(s, end, out, invalid);
bool bad = !_mm256_testz_si256(invalid, invalid);
std::size_t n[4];
for (int k = 0; k < 4; ++k) {
n[k] = done;
while (s[k] < end[k] && n[k] < kCapacity) out[k][n[k]++] = one(s[k], bad);
bad |= s[k] != end[k];
}
const auto parsed = n[0] + n[1] + n[2] + n[3];
if (bad || parsed > count) return 0;
for (int k = 0; k < 4; ++k) emit(out[k], n[k]);
p = last;
return parsed;
}
static std::size_t chunk(const char *&p, const char *limit, unsigned *dst, std::size_t count, unsigned *scratch) {
unsigned *const out[4] = {dst, scratch, scratch + kCapacity, scratch + 2 * kCapacity};
bool first = true;
unsigned *next = dst;
return chunk_blocks(p, limit, count, out, [&](const unsigned *values, std::size_t n) {
if (!first) std::memcpy(next, values, n * sizeof(unsigned));
first = false;
next += n;
});
}
template <class Emit>
static void read_blocks(FastInput &in, std::size_t count, Emit emit) {
std::unique_ptr<unsigned[]> scratch;
std::size_t done = 0;
bool chunks = true;
while (done < count) {
const char *p = in.current;
while (p != in.end && static_cast<unsigned char>(*p) <= ' ') ++p;
while (chunks && count - done >= 1024 && in.end - p >= 1088) {
if (!scratch) scratch = std::make_unique_for_overwrite<unsigned[]>(4 * kCapacity);
unsigned *const out[4] = {scratch.get(), scratch.get() + kCapacity, scratch.get() + 2 * kCapacity, scratch.get() + 3 * kCapacity};
const auto parsed = chunk_blocks(p, in.end, count - done, out, emit);
if (!parsed) {
chunks = false;
break;
}
done += parsed;
}
unsigned tail[64];
std::size_t used = 0;
while (done + 2 <= count && in.end - p >= 32) {
const char *next = p;
auto invalid = _mm256_setzero_si256();
const auto groups = two(next, invalid);
if (!_mm256_testz_si256(invalid, invalid)) break;
const auto halves = _mm256_madd_epi16(_mm256_packus_epi32(groups, groups), _mm256_set1_epi32(0x00012710));
const unsigned h0 = _mm256_extract_epi32(halves, 0), l0 = _mm256_extract_epi32(halves, 1);
const unsigned h1 = _mm256_extract_epi32(halves, 4), l1 = _mm256_extract_epi32(halves, 5);
if (h0 > 42 || (h0 == 42 && l0 > 94967295) || h1 > 42 || (h1 == 42 && l1 > 94967295)) break;
tail[used++] = h0 * 100000000 + l0;
tail[used++] = h1 * 100000000 + l1;
if (used == 64) {
emit(tail, used);
used = 0;
}
done += 2;
p = next;
}
if (used) emit(tail, used);
in.current = p;
if (done < count) {
unsigned value = 0;
in.read(value);
emit(&value, 1);
++done;
}
}
}
static void read(FastInput &in, unsigned *out, std::size_t count) {
read_blocks(in, count, [&](const unsigned *values, std::size_t n) {
std::memcpy(out, values, n * sizeof(unsigned));
out += n;
});
}
};
}
#pragma GCC pop_options
#endif
namespace fast_io_detail {
template <class Emit, std::size_t... I>
void emit_record(Emit &emit, const std::uint32_t *values, std::index_sequence<I...>) {
emit(values[I]...);
}
}
template <class Emit>
void read_unsigned_blocks(FastInput &input, std::size_t count, Emit emit) {
#if defined(__linux__) && defined(__x86_64__) && defined(__GNUC__) && !defined(__clang__)
if (__builtin_cpu_supports("avx2")) {
fast_io_detail::BulkInput::read_blocks(input, count, emit);
return;
}
#endif
std::uint32_t values[64];
while (count) {
const auto n = std::min<std::size_t>(count, 64);
for (std::size_t i = 0; i < n; ++i) input.read(values[i]);
emit(values, n);
count -= n;
}
}
inline void read_unsigned(FastInput &input, std::span<std::uint32_t> out) {
read_unsigned_blocks(input, out.size(), [&](const std::uint32_t *values, std::size_t count) {
std::memcpy(out.data(), values, count * sizeof(std::uint32_t));
out = out.subspan(count);
});
}
template <std::size_t Fields, class Emit>
void read_unsigned_records(FastInput &input, std::size_t count, Emit emit) {
static_assert(Fields > 0);
if (count > std::numeric_limits<std::size_t>::max() / Fields) throw std::length_error("input size");
std::array<std::uint32_t, Fields> pending;
std::size_t used = 0;
constexpr auto indices = std::make_index_sequence<Fields>();
read_unsigned_blocks(input, count * Fields, [&](const std::uint32_t *values, std::size_t n) {
std::size_t i = 0;
if (used) {
while (used < Fields && i < n) pending[used++] = values[i++];
if (used == Fields) {
fast_io_detail::emit_record(emit, pending.data(), indices);
used = 0;
}
}
for (; i < n && n - i >= Fields; i += Fields) fast_io_detail::emit_record(emit, values + i, indices);
while (i < n) pending[used++] = values[i++];
});
}
#line 4 "test/set_xor_min.test.cpp"
int main() {
FastInput input;
FastOutput output;
int q = 0;
input.read(q);
XorSet<> set;
read_unsigned_records<2>(input, q, [&](std::uint32_t type, std::uint32_t x) {
if (type == 0) set.insert(x);
else if (type == 1) set.erase(x);
else output.println(set.min_xor(x));
});
}