#include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr int n = 17; constexpr int word_count = 1 << n; constexpr int descendant_count = 1 << (n - 2); int delete_bit(int word, int position) { const int low = (1 << position) - 1; return (word & low) | ((word >> 1) & ~low); } struct Incidence { std::vector> descendants{word_count}; std::vector> parents{descendant_count}; Incidence() { std::vector last_seen(descendant_count, -1); for (int word = 0; word < word_count; ++word) { auto& row = descendants[word]; for (int second = 1; second < n; ++second) { const int once = delete_bit(word, second); for (int first = 0; first < second; ++first) { const int child = delete_bit(once, first); if (last_seen[child] == word) continue; last_seen[child] = word; row.push_back(static_cast(child)); parents[child].push_back(word); } } std::sort(row.begin(), row.end()); } } bool disjoint(int a, int b) const { const auto& left = descendants[a]; const auto& right = descendants[b]; auto i = left.begin(), j = right.begin(); while (i != left.end() && j != right.end()) { if (*i == *j) return false; if (*i < *j) ++i; else ++j; } return true; } }; // Dense membership with constant-time insertion, deletion, and random access. class WordSet { public: bool contains(int word) const { return positions[word] >= 0; } int size() const { return static_cast(words.size()); } int operator[](int i) const { return words[i]; } const std::vector& values() const { return words; } void add(int word) { positions[word] = size(); words.push_back(word); } void erase(int word) { const int i = positions[word]; words[i] = words.back(); positions[words[i]] = i; words.pop_back(); positions[word] = -1; } private: std::vector positions = std::vector(word_count, -1); std::vector words; }; struct Move { int word; bool added; }; class Search { public: Search(const Incidence& graph, std::uint32_t seed) : graph_(graph), random_(seed) { for (int word = 0; word < word_count; ++word) free_.add(word); } const WordSet& code() const { return code_; } void reset(const std::vector& words) { while (code_.size() > 0) erase(code_[0]); for (int word : words) insert(word); journal_.clear(); } void step(int round, int best_size) { const int previous = code_.size(); journal_.clear(); const int mode = draw(10); if (mode < 7) { const int insertions = mode < 4 ? 1 : 2 + draw(2); for (int i = 0; i < insertions; ++i) force_candidate(mode < 4 ? 2 : 4); } else { const int removals = 2 + draw(mode == 9 ? 15 : 5); for (int i = 0; i < removals; ++i) { const int a = code_[draw(code_.size())]; const int b = code_[draw(code_.size())]; drop(graph_.descendants[a].size() > graph_.descendants[b].size() ? a : b); } } const int samples = 1 + draw(18); fill(samples); const int probes = mode < 4 ? 6 : 14; for (int i = 0; i < probes; ++i) { if (one_for_two(code_[draw(code_.size())])) fill(samples); } if (round % 4 == 0 && two_for_three(code_[draw(code_.size())])) fill(samples); // A small loss can move the search off a plateau. The accepted drop // widens and narrows periodically without losing the saved incumbent. const int phase = round % 7200; const int tolerance = phase < 3100 ? 4 : (phase < 5700 ? 8 : 12); const int size = code_.size(); if (size >= previous || (size >= best_size - tolerance && size + 2 >= previous && draw(6) == 0)) { return; } for (auto i = journal_.rbegin(); i != journal_.rend(); ++i) { if (i->added) erase(i->word); else insert(i->word); } } private: int draw(int upper) { return static_cast(random_() % static_cast(upper)); } void insert(int word) { if (occupied_[word] != 0 || code_.contains(word)) throw std::logic_error("invalid insertion"); code_.add(word); for (int child : graph_.descendants[word]) { owner_[child] = word; for (int parent : graph_.parents[child]) { if (occupied_[parent]++ == 0) free_.erase(parent); } } } void erase(int word) { if (!code_.contains(word)) throw std::logic_error("invalid removal"); code_.erase(word); for (int child : graph_.descendants[word]) { owner_[child] = -1; for (int parent : graph_.parents[child]) { if (--occupied_[parent] == 0) free_.add(parent); } } } void take(int word) { insert(word); journal_.push_back({word, true}); } void drop(int word) { erase(word); journal_.push_back({word, false}); } void fill(int samples) { while (free_.size() > 0) { int best = free_[draw(free_.size())]; int cost = static_cast(graph_.descendants[best].size()) + draw(9); for (int i = 1; i < std::min(samples, free_.size()); ++i) { const int word = free_[draw(free_.size())]; const int rival = static_cast(graph_.descendants[word].size()) + draw(9); if (rival < cost) { best = word; cost = rival; } } take(best); } } // Choose a new word with few blockers and preferentially trade it for // owners using more descendants, freeing space for the greedy refill. void force_candidate(int max_blockers) { int best = -1; int best_cost = std::numeric_limits::max(); std::array best_owners{}; int best_count = 0; const int pivot = code_[draw(code_.size())]; for (int i = 0; i < 48; ++i) { int word = draw(word_count); if (i < 32) { const auto& children = graph_.descendants[pivot]; const auto& parents = graph_.parents[children[draw(static_cast(children.size()))]]; word = parents[draw(static_cast(parents.size()))]; } if (occupied_[word] == 0 || code_.contains(word)) continue; std::array owners{}; int count = 0; int released = 0; for (int child : graph_.descendants[word]) { const int owner = owner_[child]; if (owner < 0 || std::find(owners.begin(), owners.begin() + count, owner) != owners.begin() + count) continue; if (count == max_blockers) { ++count; break; } owners[count++] = owner; released += static_cast(graph_.descendants[owner].size()); } if (count > max_blockers) continue; const int cost = count * 20 + static_cast(graph_.descendants[word].size()) - released / 2 + draw(30); if (cost < best_cost) { best = word; best_cost = cost; best_owners = owners; best_count = count; } } if (best < 0) return; for (int i = 0; i < best_count; ++i) drop(best_owners[i]); take(best); } // A touched outside word is available after removing owner exactly when // the occupied children it shares with owner account for all blockers. bool one_for_two(int owner) { collect_options(owner); const int count = static_cast(options_.size()); if (count < 2) return false; const int offset = draw(count); for (int i = 0; i < count; ++i) { const int a = options_[(i + offset) % count]; for (int j = 0; j < i; ++j) { const int b = options_[(j + offset) % count]; if (!graph_.disjoint(a, b)) continue; drop(owner); take(a); take(b); return true; } } return false; } void collect_options(int first, int second = -1) { touched_.clear(); options_.clear(); for (int owner : {first, second}) { if (owner < 0) continue; for (int child : graph_.descendants[owner]) { for (int word : graph_.parents[child]) { if (shared_[word]++ == 0) touched_.push_back(word); } } } for (int word : touched_) { if (word != first && word != second && shared_[word] == occupied_[word]) options_.push_back(word); shared_[word] = 0; } } // Look for a pair of incumbents that jointly block an outside word. // After removing the pair, three compatible options are a net gain. bool two_for_three(int first) { const auto& children = graph_.descendants[first]; int second = -1; for (int attempt = 0; attempt < 48 && second < 0; ++attempt) { const auto& parents = graph_.parents[children[draw(static_cast(children.size()))]]; const int word = parents[draw(static_cast(parents.size()))]; if (code_.contains(word)) continue; for (int child : graph_.descendants[word]) { const int owner = owner_[child]; if (owner < 0 || owner == first || owner == second) continue; if (second >= 0) { second = -1; break; } second = owner; } } if (second < 0) return false; collect_options(first, second); const int count = static_cast(options_.size()); if (count < 3) return false; const int offset = draw(count); std::vector neighbors; neighbors.reserve(count); for (int i = 0; i < count; ++i) { neighbors.clear(); const int a = options_[(i + offset) % count]; for (int j = i + 1; j < count; ++j) { const int b = options_[(j + offset) % count]; if (!graph_.disjoint(a, b)) continue; for (int c : neighbors) { if (!graph_.disjoint(b, c)) continue; drop(first); drop(second); take(a); take(b); take(c); return true; } neighbors.push_back(b); } } return false; } const Incidence& graph_; std::mt19937 random_; WordSet code_; WordSet free_; std::vector owner_ = std::vector(descendant_count, -1); std::vector occupied_ = std::vector(word_count); std::vector shared_ = std::vector(word_count); std::vector touched_; std::vector options_; std::vector journal_; }; std::vector read_code(const std::filesystem::path& file) { std::ifstream input(file); if (!input) throw std::runtime_error("cannot read the starting code"); const std::string json{std::istreambuf_iterator(input), std::istreambuf_iterator()}; const std::regex word_pattern(R"re("([01]{17})")re"); std::vector result; for (std::sregex_iterator i(json.begin(), json.end(), word_pattern), end; i != end; ++i) { result.push_back(std::stoi((*i)[1], nullptr, 2)); } if (result.empty()) throw std::runtime_error("the starting code contains no words"); return result; } void write_code(const std::filesystem::path& file, std::vector words) { std::sort(words.begin(), words.end()); std::filesystem::path temporary = file; temporary += ".tmp"; std::ofstream output(temporary); output.exceptions(std::ios::failbit | std::ios::badbit); output << "{\n \"n\": " << n << ",\n \"words\": [\n"; for (std::size_t i = 0; i < words.size(); ++i) { output << " \"" << std::bitset(words[i]) << '"' << (i + 1 == words.size() ? "\n" : ",\n"); } output << " ]\n}\n"; output.close(); std::filesystem::rename(temporary, file); } } // namespace int main(int argc, char** argv) { try { if (argc != 5) throw std::runtime_error("usage: search SEED ROUNDS INPUT_JSON OUTPUT_JSON"); const auto seed = std::stoull(argv[1]); const int rounds = std::stoi(argv[2]); if (rounds < 1 || seed > std::numeric_limits::max()) throw std::runtime_error("invalid seed or round count"); auto best = read_code(argv[3]); const Incidence graph; Search search(graph, static_cast(seed)); search.reset(best); write_code(argv[4], best); std::cout << "metric: code_size " << best.size() << std::endl; for (int round = 1; round <= rounds; ++round) { if (round % 7200 == 1 && round > 1) search.reset(best); search.step(round, static_cast(best.size())); if (search.code().size() > static_cast(best.size())) { best = search.code().values(); write_code(argv[4], best); std::cout << "metric: code_size " << best.size() << "\nround " << round << std::endl; } if (round % 1000 == 0 || round == rounds) { std::cout << "progress: " << round << '/' << rounds << " rounds, best " << best.size() << std::endl; } } std::cout << "seed " << seed << ", best " << best.size() << " codewords" << std::endl; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; return 1; } }