#line 1 "verify/game/game_algorithms.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"
#line 1 "game/all.hpp"
#line 1 "game/green_hackenbush.hpp"
#include <cassert>
#include <cstdint>
#include <vector>
namespace m1une {
namespace game {
// Every vertex represents one green edge. parent[v] == -1 attaches that edge
// to the ground; otherwise it attaches it above the edge parent[v].
inline uint64_t green_hackenbush_grundy(const std::vector<int>& parent) {
const int size = int(parent.size());
std::vector<std::vector<int>> children(size);
std::vector<int> roots;
for (int edge = 0; edge < size; ++edge) {
assert(-1 <= parent[edge] && parent[edge] < size);
assert(parent[edge] != edge);
if (parent[edge] == -1) {
roots.push_back(edge);
} else {
children[parent[edge]].push_back(edge);
}
}
std::vector<int> order = roots;
order.reserve(size);
for (int position = 0; position < int(order.size()); ++position) {
const int edge = order[position];
for (int child : children[edge]) order.push_back(child);
}
assert(int(order.size()) == size);
std::vector<uint64_t> branch(size);
for (int position = size - 1; position >= 0; --position) {
const int edge = order[position];
uint64_t children_grundy = 0;
for (int child : children[edge]) children_grundy ^= branch[child];
branch[edge] = children_grundy + 1;
}
uint64_t result = 0;
for (int root : roots) result ^= branch[root];
return result;
}
inline bool green_hackenbush_first_player_wins(
const std::vector<int>& parent
) {
return green_hackenbush_grundy(parent) != 0;
}
} // namespace game
} // namespace m1une
#line 1 "game/grundy.hpp"
#line 5 "game/grundy.hpp"
#include <queue>
#line 7 "game/grundy.hpp"
namespace m1une {
namespace game {
// graph[v] contains the states reachable from v in one move.
// The graph must be a DAG.
template <typename Graph>
std::vector<int> grundy_numbers(const Graph& graph) {
const int size = int(graph.size());
std::vector<int> indegree(size);
for (int vertex = 0; vertex < size; ++vertex) {
for (int next : graph[vertex]) {
assert(0 <= next && next < size);
indegree[next]++;
}
}
std::queue<int> queue;
for (int vertex = 0; vertex < size; ++vertex) {
if (indegree[vertex] == 0) queue.push(vertex);
}
std::vector<int> order;
order.reserve(size);
while (!queue.empty()) {
const int vertex = queue.front();
queue.pop();
order.push_back(vertex);
for (int next : graph[vertex]) {
if (--indegree[next] == 0) queue.push(next);
}
}
assert(int(order.size()) == size);
std::vector<int> grundy(size);
std::vector<int> seen(size + 1, -1);
for (int position = size - 1; position >= 0; --position) {
const int vertex = order[position];
for (int next : graph[vertex]) {
const int value = grundy[next];
if (value <= size) seen[value] = vertex;
}
while (grundy[vertex] <= size && seen[grundy[vertex]] == vertex) {
grundy[vertex]++;
}
}
return grundy;
}
} // namespace game
} // namespace m1une
#line 1 "game/minimax.hpp"
#line 6 "game/minimax.hpp"
#include <utility>
#line 8 "game/minimax.hpp"
namespace m1une {
namespace game {
template <typename T>
struct MinimaxResult {
std::vector<T> value;
std::vector<int> move;
};
template <typename T>
MinimaxResult<T> dag_minimax(
const std::vector<std::vector<int>>& graph,
const std::vector<T>& terminal_value,
const std::vector<bool>& maximize
) {
const int size = int(graph.size());
assert(int(terminal_value.size()) == size);
assert(int(maximize.size()) == size);
std::vector<int> indegree(size);
for (int vertex = 0; vertex < size; ++vertex) {
for (int next : graph[vertex]) {
assert(0 <= next && next < size);
indegree[next]++;
}
}
std::queue<int> queue;
for (int vertex = 0; vertex < size; ++vertex) {
if (indegree[vertex] == 0) queue.push(vertex);
}
std::vector<int> order;
order.reserve(size);
while (!queue.empty()) {
const int vertex = queue.front();
queue.pop();
order.push_back(vertex);
for (int next : graph[vertex]) {
if (--indegree[next] == 0) queue.push(next);
}
}
assert(int(order.size()) == size);
std::vector<T> value = terminal_value;
std::vector<int> move(size, -1);
for (int position = size - 1; position >= 0; --position) {
const int vertex = order[position];
if (graph[vertex].empty()) {
value[vertex] = terminal_value[vertex];
continue;
}
move[vertex] = graph[vertex][0];
value[vertex] = value[move[vertex]];
for (int next : graph[vertex]) {
const bool improves = maximize[vertex]
? value[vertex] < value[next]
: value[next] < value[vertex];
if (improves) {
value[vertex] = value[next];
move[vertex] = next;
}
}
}
return {std::move(value), std::move(move)};
}
} // namespace game
} // namespace m1une
#line 1 "game/nim.hpp"
#include <iterator>
#include <optional>
#include <type_traits>
#line 8 "game/nim.hpp"
namespace m1une {
namespace game {
template <typename T>
struct NimMove {
int heap;
T new_size;
};
template <typename Iterator>
auto nim_sum(Iterator first, Iterator last) {
using T = typename std::iterator_traits<Iterator>::value_type;
T result{};
while (first != last) {
result ^= *first;
++first;
}
return result;
}
template <typename Range>
auto nim_sum(const Range& heaps) {
using std::begin;
using std::end;
return nim_sum(begin(heaps), end(heaps));
}
template <typename Range>
bool nim_first_player_wins(const Range& heaps) {
return nim_sum(heaps) != 0;
}
template <typename Range>
auto nim_winning_move(const Range& heaps) {
using std::begin;
using std::end;
using T = std::decay_t<decltype(*begin(heaps))>;
const T sum = nim_sum(heaps);
if (sum == 0) return std::optional<NimMove<T>>{};
int index = 0;
for (
auto iterator = begin(heaps);
iterator != end(heaps);
++iterator, ++index
) {
const T new_size = *iterator ^ sum;
if (new_size < *iterator) return std::optional(NimMove<T>{index, new_size});
}
return std::optional<NimMove<T>>{};
}
template <typename Range>
bool misere_nim_first_player_wins(const Range& heaps) {
using std::begin;
using std::end;
auto first = begin(heaps);
const auto last = end(heaps);
bool odd_nonzero_heaps = false;
bool has_large_heap = false;
using T = typename std::iterator_traits<decltype(first)>::value_type;
T sum{};
for (; first != last; ++first) {
sum ^= *first;
if (*first != 0) {
odd_nonzero_heaps = !odd_nonzero_heaps;
}
if (*first > 1) has_large_heap = true;
}
return has_large_heap ? sum != 0 : !odd_nonzero_heaps;
}
template <typename Range>
auto misere_nim_winning_move(const Range& heaps) {
using std::begin;
using std::end;
using T = std::decay_t<decltype(*begin(heaps))>;
T sum{};
int ones = 0;
int large_heaps = 0;
int only_large_heap = -1;
int index = 0;
for (
auto iterator = begin(heaps);
iterator != end(heaps);
++iterator, ++index
) {
sum ^= *iterator;
if (*iterator == 1) ones++;
if (*iterator > 1) {
large_heaps++;
only_large_heap = index;
}
}
if (large_heaps == 0) {
if (ones == 0 || ones % 2 == 1) return std::optional<NimMove<T>>{};
index = 0;
for (
auto iterator = begin(heaps);
iterator != end(heaps);
++iterator, ++index
) {
if (*iterator == 1) return std::optional(NimMove<T>{index, T(0)});
}
}
if (large_heaps == 1) {
const T new_size = ones % 2 == 0 ? T(1) : T(0);
return std::optional(NimMove<T>{only_large_heap, new_size});
}
if (sum == 0) return std::optional<NimMove<T>>{};
index = 0;
for (auto iterator = begin(heaps); iterator != end(heaps); ++iterator, ++index) {
const T new_size = *iterator ^ sum;
if (new_size < *iterator) return std::optional(NimMove<T>{index, new_size});
}
return std::optional<NimMove<T>>{};
}
} // namespace game
} // namespace m1une
#line 1 "game/nim_product.hpp"
#include <array>
#line 7 "game/nim_product.hpp"
#include <limits>
namespace m1une {
namespace game {
namespace internal {
inline uint64_t nim_product_small(uint64_t x, uint64_t y) {
if (x < 2 || y < 2) return x * y;
int shift = 1;
const uint64_t largest = x | y;
while ((uint64_t(1) << (shift * 2)) <= largest) shift *= 2;
const uint64_t mask = (uint64_t(1) << shift) - 1;
const uint64_t x_high = x >> shift;
const uint64_t x_low = x & mask;
const uint64_t y_high = y >> shift;
const uint64_t y_low = y & mask;
const uint64_t high_product = nim_product_small(x_high, y_high);
const uint64_t low_product = nim_product_small(x_low, y_low);
const uint64_t mixed_product =
nim_product_small(x_high ^ x_low, y_high ^ y_low);
return ((mixed_product ^ low_product) << shift) ^ low_product
^ nim_product_small(high_product, uint64_t(1) << (shift - 1));
}
inline const std::array<uint8_t, 1 << 16>& nim_product_8_table() {
static const auto table = [] {
std::array<uint8_t, 1 << 16> result{};
for (int x = 0; x < 256; ++x) {
for (int y = 0; y < 256; ++y) {
result[(x << 8) | y] = uint8_t(nim_product_small(x, y));
}
}
return result;
}();
return table;
}
inline uint64_t nim_product_8(uint64_t x, uint64_t y) {
return nim_product_8_table()[(x << 8) | y];
}
template <int Bits>
inline uint64_t nim_product_fixed(uint64_t x, uint64_t y) {
if constexpr (Bits == 8) {
return nim_product_8(x, y);
} else {
constexpr int shift = Bits / 2;
constexpr uint64_t mask = (uint64_t(1) << shift) - 1;
const uint64_t x_high = x >> shift;
const uint64_t x_low = x & mask;
const uint64_t y_high = y >> shift;
const uint64_t y_low = y & mask;
const uint64_t high_product =
nim_product_fixed<shift>(x_high, y_high);
const uint64_t low_product = nim_product_fixed<shift>(x_low, y_low);
const uint64_t mixed_product = nim_product_fixed<shift>(
x_high ^ x_low,
y_high ^ y_low
);
return ((mixed_product ^ low_product) << shift) ^ low_product
^ nim_product_fixed<shift>(
high_product,
uint64_t(1) << (shift - 1)
);
}
}
} // namespace internal
inline uint64_t nim_product(uint64_t x, uint64_t y) {
return internal::nim_product_fixed<64>(x, y);
}
inline uint64_t nim_power(uint64_t base, uint64_t exponent) {
uint64_t result = 1;
while (exponent != 0) {
if (exponent & 1) result = nim_product(result, base);
base = nim_product(base, base);
exponent >>= 1;
}
return result;
}
inline uint64_t nim_inverse(uint64_t value) {
assert(value != 0);
return nim_power(value, std::numeric_limits<uint64_t>::max() - 1);
}
inline uint64_t nim_quotient(uint64_t numerator, uint64_t denominator) {
assert(denominator != 0);
return nim_product(numerator, nim_inverse(denominator));
}
} // namespace game
} // namespace m1une
#line 1 "game/partisan_game.hpp"
#line 7 "game/partisan_game.hpp"
namespace m1une {
namespace game {
enum class PartisanOutcome { Left, Right, Next, Previous };
inline std::vector<PartisanOutcome> partisan_outcomes(
const std::vector<std::vector<int>>& left_moves,
const std::vector<std::vector<int>>& right_moves
) {
const int size = int(left_moves.size());
assert(int(right_moves.size()) == size);
std::vector<int> indegree(size);
for (int vertex = 0; vertex < size; ++vertex) {
for (int next : left_moves[vertex]) {
assert(0 <= next && next < size);
indegree[next]++;
}
for (int next : right_moves[vertex]) {
assert(0 <= next && next < size);
indegree[next]++;
}
}
std::queue<int> queue;
for (int vertex = 0; vertex < size; ++vertex) {
if (indegree[vertex] == 0) queue.push(vertex);
}
std::vector<int> order;
order.reserve(size);
while (!queue.empty()) {
const int vertex = queue.front();
queue.pop();
order.push_back(vertex);
for (int next : left_moves[vertex]) {
if (--indegree[next] == 0) queue.push(next);
}
for (int next : right_moves[vertex]) {
if (--indegree[next] == 0) queue.push(next);
}
}
assert(int(order.size()) == size);
std::vector<bool> left_wins_moving(size);
std::vector<bool> left_wins_waiting(size);
std::vector<PartisanOutcome> outcome(size);
for (int position = size - 1; position >= 0; --position) {
const int vertex = order[position];
for (int next : left_moves[vertex]) {
if (left_wins_waiting[next]) left_wins_moving[vertex] = true;
}
left_wins_waiting[vertex] = true;
for (int next : right_moves[vertex]) {
if (!left_wins_moving[next]) left_wins_waiting[vertex] = false;
}
if (left_wins_moving[vertex] && left_wins_waiting[vertex]) {
outcome[vertex] = PartisanOutcome::Left;
} else if (!left_wins_moving[vertex] && !left_wins_waiting[vertex]) {
outcome[vertex] = PartisanOutcome::Right;
} else if (left_wins_moving[vertex]) {
outcome[vertex] = PartisanOutcome::Next;
} else {
outcome[vertex] = PartisanOutcome::Previous;
}
}
return outcome;
}
} // namespace game
} // namespace m1une
#line 1 "game/retrograde_analysis.hpp"
#line 8 "game/retrograde_analysis.hpp"
namespace m1une {
namespace game {
enum class GameOutcome { Win, Lose, Draw };
struct RetrogradeResult {
std::vector<GameOutcome> outcome;
std::vector<int> distance;
std::vector<int> move;
};
// graph[v] contains the states reachable from v in one move.
inline RetrogradeResult retrograde_analysis(
const std::vector<std::vector<int>>& graph
) {
const int size = int(graph.size());
std::vector<std::vector<int>> reverse_graph(size);
std::vector<int> remaining(size);
for (int vertex = 0; vertex < size; ++vertex) {
remaining[vertex] = int(graph[vertex].size());
for (int next : graph[vertex]) {
assert(0 <= next && next < size);
reverse_graph[next].push_back(vertex);
}
}
std::vector<GameOutcome> outcome(size, GameOutcome::Draw);
std::vector<int> distance(size, -1);
std::vector<int> move(size, -1);
std::vector<int> longest_win_successor(size);
std::vector<int> longest_win_move(size, -1);
std::vector<bool> decided(size);
std::queue<int> queue;
for (int vertex = 0; vertex < size; ++vertex) {
if (remaining[vertex] == 0) {
outcome[vertex] = GameOutcome::Lose;
distance[vertex] = 0;
decided[vertex] = true;
queue.push(vertex);
}
}
while (!queue.empty()) {
const int vertex = queue.front();
queue.pop();
for (int previous : reverse_graph[vertex]) {
if (decided[previous]) continue;
if (outcome[vertex] == GameOutcome::Lose) {
outcome[previous] = GameOutcome::Win;
distance[previous] = distance[vertex] + 1;
move[previous] = vertex;
decided[previous] = true;
queue.push(previous);
} else {
if (longest_win_move[previous] == -1
|| longest_win_successor[previous] < distance[vertex]) {
longest_win_successor[previous] = distance[vertex];
longest_win_move[previous] = vertex;
}
if (--remaining[previous] == 0) {
outcome[previous] = GameOutcome::Lose;
distance[previous] = longest_win_successor[previous] + 1;
move[previous] = longest_win_move[previous];
decided[previous] = true;
queue.push(previous);
}
}
}
}
for (int vertex = 0; vertex < size; ++vertex) {
if (outcome[vertex] != GameOutcome::Draw) continue;
for (int next : graph[vertex]) {
if (outcome[next] == GameOutcome::Draw) {
move[vertex] = next;
break;
}
}
}
return {std::move(outcome), std::move(distance), std::move(move)};
}
} // namespace game
} // namespace m1une
#line 1 "game/silver_dollar_game.hpp"
#line 7 "game/silver_dollar_game.hpp"
namespace m1une {
namespace game {
template <typename T>
T silver_dollar_grundy(const std::vector<T>& coins) {
for (int index = 0; index < int(coins.size()); ++index) {
if constexpr (std::is_signed_v<T>) assert(coins[index] >= 0);
if (index != 0) assert(coins[index - 1] < coins[index]);
}
T result{};
int index = int(coins.size()) % 2;
if (index == 1) result ^= coins[0];
for (; index + 1 < int(coins.size()); index += 2) {
result ^= coins[index + 1] - coins[index] - 1;
}
return result;
}
template <typename T>
bool silver_dollar_first_player_wins(const std::vector<T>& coins) {
return silver_dollar_grundy(coins) != 0;
}
} // namespace game
} // namespace m1une
#line 1 "game/subtraction_game.hpp"
#include <algorithm>
#line 7 "game/subtraction_game.hpp"
namespace m1une {
namespace game {
inline std::vector<int> subtraction_game_grundy(
int max_heap,
const std::vector<int>& moves
) {
assert(max_heap >= 0);
for (int move : moves) assert(move > 0);
std::vector<int> grundy(max_heap + 1);
std::vector<int> seen(moves.size() + 1, -1);
for (int heap = 1; heap <= max_heap; ++heap) {
for (int move : moves) {
if (move > heap) continue;
const int value = grundy[heap - move];
if (value < int(seen.size())) seen[value] = heap;
}
while (
grundy[heap] < int(seen.size())
&& seen[grundy[heap]] == heap
) {
grundy[heap]++;
}
}
return grundy;
}
inline int subtraction_game_nim_sum(
const std::vector<int>& heaps,
const std::vector<int>& moves
) {
int max_heap = 0;
for (int heap : heaps) {
assert(heap >= 0);
max_heap = std::max(max_heap, heap);
}
const std::vector<int> grundy = subtraction_game_grundy(max_heap, moves);
int result = 0;
for (int heap : heaps) result ^= grundy[heap];
return result;
}
inline bool subtraction_game_first_player_wins(
const std::vector<int>& heaps,
const std::vector<int>& moves
) {
return subtraction_game_nim_sum(heaps, moves) != 0;
}
} // namespace game
} // namespace m1une
#line 13 "game/all.hpp"
#line 4 "verify/game/game_algorithms.test.cpp"
#line 1 "utilities/fast_io.hpp"
#line 6 "utilities/fast_io.hpp"
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#line 12 "utilities/fast_io.hpp"
#include <cstring>
#line 14 "utilities/fast_io.hpp"
#include <string>
#include <sys/stat.h>
#line 18 "utilities/fast_io.hpp"
#include <unistd.h>
#line 20 "utilities/fast_io.hpp"
namespace m1une {
namespace utilities {
struct FastOutput;
namespace internal {
// Shared with the convenience helpers in template.hpp.
inline FastOutput* standard_output_instance = nullptr;
// Detect std::begin(x), std::end(x).
template <class T, class = void>
struct is_range : std::false_type {};
template <class T>
struct is_range<T, std::void_t<
decltype(std::begin(std::declval<T&>())),
decltype(std::end(std::declval<T&>()))
>> : std::true_type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;
template <class T>
using range_reference_t = decltype(*std::begin(std::declval<T&>()));
template <class T>
using range_value_t = std::remove_cv_t<std::remove_reference_t<range_reference_t<T>>>;
template <class T, class = void>
struct range_stored_value {
using type = range_value_t<T>;
};
template <class T>
struct range_stored_value<T, std::void_t<typename std::remove_cv_t<std::remove_reference_t<T>>::value_type>> {
using type = typename std::remove_cv_t<std::remove_reference_t<T>>::value_type;
};
template <class T>
using range_stored_value_t = typename range_stored_value<T>::type;
// Treat strings and C strings as scalar output objects, not as ranges.
template <class T>
struct is_char_array : std::false_type {};
template <class T, std::size_t N>
struct is_char_array<T[N]>
: std::bool_constant<std::is_same_v<std::remove_cv_t<T>, char>> {};
template <class T>
struct is_string_like
: std::bool_constant<
std::is_same_v<std::decay_t<T>, std::string>
|| std::is_same_v<std::decay_t<T>, const char*>
|| std::is_same_v<std::decay_t<T>, char*>
|| is_char_array<std::remove_reference_t<T>>::value
> {};
template <class T>
inline constexpr bool is_string_like_v = is_string_like<T>::value;
// ModInt-like type: x.val() is printable, and x can be assigned from long long.
template <class T, class = void>
struct has_val_method : std::false_type {};
template <class T>
struct has_val_method<T, std::void_t<decltype(std::declval<const T&>().val())>>
: std::true_type {};
template <class T>
inline constexpr bool has_val_method_v = has_val_method<T>::value;
template <class T, class = void>
struct has_static_mod_raw : std::false_type {};
template <class T>
struct has_static_mod_raw<
T, std::void_t<decltype(T::mod()), decltype(T::raw(std::declval<uint32_t>()))>>
: std::true_type {};
template <class T>
inline constexpr bool has_static_mod_raw_v = has_static_mod_raw<T>::value;
// libstdc++ before GCC 16 does not classify __int128 as an integral type in
// strict ISO modes such as -std=c++23. Keep the fast-I/O interface independent
// of that implementation detail.
template <class T>
inline constexpr bool is_integral_v =
std::is_integral_v<T>
|| std::is_same_v<std::remove_cv_t<T>, __int128_t>
|| std::is_same_v<std::remove_cv_t<T>, __uint128_t>;
template <class T>
inline constexpr bool is_signed_v =
std::is_signed_v<T>
|| std::is_same_v<std::remove_cv_t<T>, __int128_t>;
template <class T>
struct make_unsigned {
using type = std::make_unsigned_t<T>;
};
template <>
struct make_unsigned<__int128_t> {
using type = __uint128_t;
};
template <>
struct make_unsigned<__uint128_t> {
using type = __uint128_t;
};
template <class T>
using make_unsigned_t = typename make_unsigned<std::remove_cv_t<T>>::type;
} // namespace internal
struct FastInput {
static constexpr int buffer_size = 1 << 20;
private:
std::FILE* _stream;
char _buffer[buffer_size];
int _position;
int _length;
int _file_descriptor;
bool _streaming;
bool refill() {
_position = 0;
if (_streaming) {
ssize_t length;
do {
length = ::read(_file_descriptor, _buffer, buffer_size);
} while (length < 0 && errno == EINTR);
if (length <= 0) {
_length = 0;
return false;
}
_length = int(length);
} else {
_length = int(std::fread(_buffer, 1, buffer_size, _stream));
}
return _length != 0;
}
template <class T>
bool read_integer_from_stream(T& value) {
if (!skip_spaces()) return false;
int c = read_char_raw();
bool negative = false;
if (c == '-') {
negative = true;
c = read_char_raw();
}
if constexpr (internal::is_signed_v<T>) {
T result = 0;
while ('0' <= c && c <= '9') {
result = negative ? result * 10 - (c - '0')
: result * 10 + (c - '0');
c = read_char_raw();
}
value = result;
} else {
T result = 0;
while ('0' <= c && c <= '9') {
result = result * 10 + T(c - '0');
c = read_char_raw();
}
value = negative ? T(0) - result : result;
}
return true;
}
bool prepare_number() {
if (_length - _position >= 64) return true;
const int remaining = _length - _position;
if (remaining > 0) std::memmove(_buffer, _buffer + _position, remaining);
const int added = int(std::fread(_buffer + remaining, 1, buffer_size - remaining, _stream));
_position = 0;
_length = remaining + added;
if (_length < buffer_size) _buffer[_length] = '\0';
return _length != 0;
}
public:
explicit FastInput(std::FILE* stream = stdin)
: _stream(stream),
_position(0),
_length(0),
_file_descriptor(::fileno(stream)),
_streaming([&] {
struct stat status;
return _file_descriptor >= 0
&& ::fstat(_file_descriptor, &status) == 0
&& !S_ISREG(status.st_mode);
}()) {}
FastInput(const FastInput&) = delete;
FastInput& operator=(const FastInput&) = delete;
int read_char_raw() {
if (_position == _length && !refill()) return EOF;
return _buffer[_position++];
}
bool skip_spaces() {
int c = read_char_raw();
while (c != EOF && c <= ' ') c = read_char_raw();
if (c == EOF) return false;
--_position;
return true;
}
bool read(char& value) {
if (!skip_spaces()) return false;
value = char(read_char_raw());
return true;
}
bool read(std::string& value) {
if (!skip_spaces()) return false;
value.clear();
while (true) {
const int begin = _position;
while (_position < _length &&
static_cast<unsigned char>(_buffer[_position]) > ' ') {
++_position;
}
value.append(_buffer + begin, _position - begin);
if (_position < _length) {
++_position;
return true;
}
if (!refill()) return true;
}
}
bool read(bool& value) {
int x;
if (!read(x)) return false;
value = x != 0;
return true;
}
template <class T>
std::enable_if_t<
internal::is_integral_v<T>
&& !std::is_same_v<std::remove_cv_t<T>, bool>
&& !std::is_same_v<std::remove_cv_t<T>, char>,
bool
>
read(T& value) {
if (_streaming) return read_integer_from_stream(value);
if (!prepare_number()) return false;
int c = static_cast<unsigned char>(_buffer[_position++]);
while (c <= ' ') c = static_cast<unsigned char>(_buffer[_position++]);
bool negative = false;
if (c == '-') {
negative = true;
c = static_cast<unsigned char>(_buffer[_position++]);
}
if constexpr (internal::is_signed_v<T>) {
T result = 0;
while ('0' <= c && c <= '9') {
const int first = c - '0';
const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
if (0 <= second && second <= 9) {
result = negative ? result * 100 - (first * 10 + second)
: result * 100 + (first * 10 + second);
++_position;
} else {
result = negative ? result * 10 - first : result * 10 + first;
}
c = static_cast<unsigned char>(_buffer[_position++]);
}
value = result;
} else {
T result = 0;
while ('0' <= c && c <= '9') {
const unsigned first = unsigned(c - '0');
const int second = static_cast<unsigned char>(_buffer[_position]) - '0';
if (0 <= second && second <= 9) {
result = result * 100 + T(first * 10 + unsigned(second));
++_position;
} else {
result = result * 10 + T(first);
}
c = static_cast<unsigned char>(_buffer[_position++]);
}
value = negative ? T(0) - result : result;
}
if (_position > _length) _position = _length;
return true;
}
template <class T>
std::enable_if_t<std::is_floating_point_v<T>, bool>
read(T& value) {
if (!skip_spaces()) return false;
int c = read_char_raw();
bool negative = false;
if (c == '-' || c == '+') {
negative = c == '-';
c = read_char_raw();
}
long double result = 0;
while ('0' <= c && c <= '9') {
result = result * 10 + (c - '0');
c = read_char_raw();
}
if (c == '.') {
long double place = 0.1L;
c = read_char_raw();
while ('0' <= c && c <= '9') {
result += (c - '0') * place;
place *= 0.1L;
c = read_char_raw();
}
}
if (c == 'e' || c == 'E') {
c = read_char_raw();
bool exponent_negative = false;
if (c == '-' || c == '+') {
exponent_negative = c == '-';
c = read_char_raw();
}
int exponent = 0;
while ('0' <= c && c <= '9') {
exponent = exponent * 10 + (c - '0');
c = read_char_raw();
}
long double scale = 1;
long double power = 10;
while (exponent > 0) {
if (exponent & 1) scale *= power;
power *= power;
exponent >>= 1;
}
result = exponent_negative ? result / scale : result * scale;
}
value = static_cast<T>(negative ? -result : result);
return true;
}
template <class T>
std::enable_if_t<
internal::has_val_method_v<T>
&& !internal::is_integral_v<T>
&& !internal::is_range_v<T>,
bool
>
read(T& value) {
long long x;
if (!read(x)) return false;
if constexpr (internal::has_static_mod_raw_v<T>) {
if (x >= 0 && uint64_t(x) < uint64_t(T::mod())) {
value = T::raw(uint32_t(x));
} else {
value = T(x);
}
} else {
value = T(x);
}
return true;
}
template <class First, class Second>
bool read(std::pair<First, Second>& value) {
if (!read(value.first)) return false;
return read(value.second);
}
template <class Range>
std::enable_if_t<
internal::is_range_v<Range>
&& !internal::is_string_like_v<Range>,
bool
>
read(Range& range) {
using StoredValue = internal::range_stored_value_t<Range>;
constexpr bool nested = internal::is_range_v<StoredValue>
&& !internal::is_string_like_v<StoredValue>;
for (auto&& value : range) {
if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
bool x;
if (!read(x)) return false;
value = x;
} else {
if (!read(value)) return false;
}
}
return true;
}
template <class First, class Second, class... Rest>
bool read(First& first, Second& second, Rest&... rest) {
if (!read(first)) return false;
return read(second, rest...);
}
template <class T>
FastInput& operator>>(T& value) {
if (!read(value)) std::abort();
return *this;
}
};
struct FastOutput {
static constexpr int buffer_size = 1 << 20;
private:
inline static const auto digit_quads = [] {
std::array<char, 40000> result{};
for (int i = 0; i < 10000; i++) {
int value = i;
for (int j = 3; j >= 0; j--) {
result[4 * i + j] = char('0' + value % 10);
value /= 10;
}
}
return result;
}();
std::FILE* _stream;
char _buffer[buffer_size];
int _position;
int _precision;
std::chars_format _float_format;
char _range_separator;
std::string* _capture = nullptr;
template <class T>
std::string format_cell(const T& value) {
std::string result;
struct CaptureGuard {
std::string*& target;
std::string* previous;
~CaptureGuard() { target = previous; }
} guard{_capture, _capture};
_capture = &result;
write(value);
return result;
}
template <class Matrix>
void write_aligned_matrix(const Matrix& matrix) {
std::vector<std::vector<std::string>> rows;
std::vector<std::size_t> widths;
for (const auto& row : matrix) {
auto& cells = rows.emplace_back();
std::size_t column = 0;
for (const auto& value : row) {
cells.push_back(format_cell(value));
if (column == widths.size()) widths.push_back(0);
widths[column] = std::max(widths[column], cells.back().size());
++column;
}
}
bool first = true;
for (const auto& row : rows) {
if (!first) write_char('\n');
first = false;
for (std::size_t column = 0; column < row.size(); ++column) {
if (column != 0) write_char(_range_separator);
for (std::size_t padding = row[column].size();
padding < widths[column]; ++padding) {
write_char(' ');
}
write(row[column]);
}
}
}
public:
explicit FastOutput(std::FILE* stream = stdout)
: _stream(stream),
_position(0),
_precision(6),
_float_format(std::chars_format::general),
_range_separator(' ') {
if (_stream == stdout
&& internal::standard_output_instance == nullptr) {
internal::standard_output_instance = this;
}
}
FastOutput(const FastOutput&) = delete;
FastOutput& operator=(const FastOutput&) = delete;
~FastOutput() {
flush();
if (internal::standard_output_instance == this) {
internal::standard_output_instance = nullptr;
}
}
void flush() {
if (_position != 0) {
std::fwrite(_buffer, 1, _position, _stream);
_position = 0;
}
std::fflush(_stream);
}
void write_char(char c) {
if (_capture != nullptr) {
_capture->push_back(c);
return;
}
if (_position == buffer_size) flush();
_buffer[_position++] = c;
}
void write(const char* s) {
while (*s != '\0') write_char(*s++);
}
void write(const std::string& s) {
if (_capture != nullptr) {
_capture->append(s);
return;
}
std::size_t position = 0;
while (position < s.size()) {
if (_position == buffer_size) flush();
const std::size_t copied =
std::min<std::size_t>(buffer_size - _position, s.size() - position);
std::memcpy(_buffer + _position, s.data() + position, copied);
_position += int(copied);
position += copied;
}
}
void write(char c) {
write_char(c);
}
void write(bool value) {
write_char(value ? '1' : '0');
}
template <class T>
std::enable_if_t<std::is_floating_point_v<T>>
write(T value) {
char digits[128];
auto [end, error] = std::to_chars(
digits,
digits + sizeof(digits),
value,
_float_format,
_precision
);
if (error != std::errc()) std::abort();
for (const char* pointer = digits; pointer != end; pointer++) {
write_char(*pointer);
}
}
template <class T>
std::enable_if_t<
internal::is_integral_v<T>
&& !std::is_same_v<std::remove_cv_t<T>, bool>
&& !std::is_same_v<std::remove_cv_t<T>, char>
>
write(T value) {
using Raw = std::remove_cv_t<T>;
using Unsigned = internal::make_unsigned_t<Raw>;
Unsigned magnitude;
if constexpr (internal::is_signed_v<Raw>) {
if (value < 0) {
write_char('-');
magnitude = Unsigned(0) - Unsigned(value);
} else {
magnitude = Unsigned(value);
}
} else {
magnitude = value;
}
if (magnitude == 0) {
write_char('0');
return;
}
unsigned chunks[16];
int count = 0;
while (magnitude >= 10000) {
const Unsigned quotient = magnitude / 10000;
chunks[count++] = unsigned(magnitude - quotient * 10000);
magnitude = quotient;
}
if (_capture == nullptr && _position > buffer_size - 64) flush();
char captured[64];
char* const begin = _capture != nullptr ? captured : _buffer + _position;
char* destination = begin;
const unsigned leading = unsigned(magnitude);
const char* first = digit_quads.data() + 4 * leading;
int skip = leading < 10 ? 3 : leading < 100 ? 2 : leading < 1000 ? 1 : 0;
for (; skip < 4; skip++) *destination++ = first[skip];
while (count--) {
const char* digits = digit_quads.data() + 4 * chunks[count];
std::memcpy(destination, digits, 4);
destination += 4;
}
if (_capture != nullptr) {
_capture->append(begin, destination - begin);
} else {
_position += int(destination - begin);
}
}
template <class T>
std::enable_if_t<
internal::has_val_method_v<T>
&& !internal::is_integral_v<T>
&& !internal::is_range_v<T>
>
write(const T& value) {
write(value.val());
}
template <class First, class Second>
void write(const std::pair<First, Second>& value) {
write(value.first);
write_char(' ');
write(value.second);
}
template <class Range>
std::enable_if_t<
internal::is_range_v<Range>
&& !internal::is_string_like_v<Range>
>
write(const Range& range) {
using StoredValue = internal::range_stored_value_t<const Range>;
constexpr bool nested = internal::is_range_v<StoredValue>
&& !internal::is_string_like_v<StoredValue>;
bool first = true;
for (const auto& value : range) {
if (!first) write_char(nested ? '\n' : _range_separator);
first = false;
if constexpr (std::is_same_v<StoredValue, bool> && !nested) {
write(static_cast<bool>(value));
} else {
write(value);
}
}
}
template <class First, class... Rest>
void print(const First& first, const Rest&... rest) {
write(first);
((write_char(' '), write(rest)), ...);
}
void println() {
write_char('\n');
}
void set_precision(int precision) {
_precision = precision;
}
void set_fixed(int precision = 6) {
_float_format = std::chars_format::fixed;
_precision = precision;
}
void set_general(int precision = 6) {
_float_format = std::chars_format::general;
_precision = precision;
}
void set_range_separator(char separator) {
_range_separator = separator;
}
template <class Matrix>
void write_aligned(const Matrix& matrix) {
using Row = internal::range_stored_value_t<const Matrix>;
using Cell = internal::range_stored_value_t<const Row>;
static_assert(internal::is_range_v<Row> && !internal::is_string_like_v<Row>,
"write_aligned requires a two-dimensional range");
static_assert(!internal::is_range_v<Cell> || internal::is_string_like_v<Cell>,
"write_aligned requires scalar cells");
write_aligned_matrix(matrix);
}
template <class Matrix>
void println_aligned(const Matrix& matrix) {
write_aligned(matrix);
write_char('\n');
}
template <class... Args>
void println(const Args&... args) {
print(args...);
write_char('\n');
}
template <class T>
FastOutput& operator<<(const T& value) {
write(value);
return *this;
}
};
} // namespace utilities
} // namespace m1une
#line 9 "verify/game/game_algorithms.test.cpp"
#include <random>
#line 11 "verify/game/game_algorithms.test.cpp"
namespace {
using m1une::game::GameOutcome;
void test_nim() {
std::vector<int> empty;
assert(m1une::game::nim_sum(empty) == 0);
assert(!m1une::game::nim_first_player_wins(empty));
assert(m1une::game::misere_nim_first_player_wins(empty));
std::vector<int> ordinary = {1, 4, 5};
assert(m1une::game::nim_sum(ordinary) == 0);
assert(!m1une::game::nim_first_player_wins(ordinary));
std::vector<int> one_one = {1, 1};
std::vector<int> one_one_one = {1, 1, 1};
assert(m1une::game::misere_nim_first_player_wins(one_one));
assert(!m1une::game::misere_nim_first_player_wins(one_one_one));
std::vector<int> general = {1, 2, 3};
assert(!m1une::game::misere_nim_first_player_wins(general));
for (int code = 0; code < 625; ++code) {
int remaining = code;
std::vector<int> heaps(4);
for (int& heap : heaps) {
heap = remaining % 5;
remaining /= 5;
}
auto ordinary_move = m1une::game::nim_winning_move(heaps);
assert(bool(ordinary_move) == m1une::game::nim_first_player_wins(heaps));
if (ordinary_move) {
assert(0 <= ordinary_move->heap && ordinary_move->heap < 4);
assert(ordinary_move->new_size < heaps[ordinary_move->heap]);
heaps[ordinary_move->heap] = ordinary_move->new_size;
assert(!m1une::game::nim_first_player_wins(heaps));
}
remaining = code;
for (int& heap : heaps) {
heap = remaining % 5;
remaining /= 5;
}
const bool has_stone = std::any_of(
heaps.begin(),
heaps.end(),
[](int heap) { return heap != 0; }
);
auto misere_move = m1une::game::misere_nim_winning_move(heaps);
assert(
bool(misere_move)
== (has_stone && m1une::game::misere_nim_first_player_wins(heaps))
);
if (misere_move) {
assert(0 <= misere_move->heap && misere_move->heap < 4);
assert(misere_move->new_size < heaps[misere_move->heap]);
heaps[misere_move->heap] = misere_move->new_size;
assert(!m1une::game::misere_nim_first_player_wins(heaps));
}
}
}
std::vector<int> naive_grundy(const std::vector<std::vector<int>>& graph) {
const int size = int(graph.size());
std::vector<int> result(size);
for (int vertex = size - 1; vertex >= 0; --vertex) {
std::vector<bool> appears(size + 1);
for (int next : graph[vertex]) appears[result[next]] = true;
while (appears[result[vertex]]) result[vertex]++;
}
return result;
}
void test_grundy_random() {
std::mt19937 random(123456789);
for (int size = 0; size <= 40; ++size) {
for (int trial = 0; trial < 100; ++trial) {
std::vector<std::vector<int>> graph(size);
for (int from = 0; from < size; ++from) {
for (int to = from + 1; to < size; ++to) {
if (random() % 5 == 0) graph[from].push_back(to);
}
}
assert(m1une::game::grundy_numbers(graph) == naive_grundy(graph));
}
}
}
std::vector<GameOutcome> naive_outcomes(
const std::vector<std::vector<int>>& graph
) {
const int size = int(graph.size());
std::vector<GameOutcome> result(size, GameOutcome::Draw);
std::vector<bool> decided(size);
for (int vertex = 0; vertex < size; ++vertex) {
if (graph[vertex].empty()) {
result[vertex] = GameOutcome::Lose;
decided[vertex] = true;
}
}
bool changed = true;
while (changed) {
changed = false;
for (int vertex = 0; vertex < size; ++vertex) {
if (decided[vertex]) continue;
bool has_losing_move = false;
bool all_moves_win = true;
for (int next : graph[vertex]) {
has_losing_move |= decided[next] && result[next] == GameOutcome::Lose;
all_moves_win &= decided[next] && result[next] == GameOutcome::Win;
}
if (has_losing_move || all_moves_win) {
result[vertex] = has_losing_move ? GameOutcome::Win : GameOutcome::Lose;
decided[vertex] = true;
changed = true;
}
}
}
return result;
}
void test_retrograde_random() {
std::mt19937 random(987654321);
for (int size = 0; size <= 30; ++size) {
for (int trial = 0; trial < 100; ++trial) {
std::vector<std::vector<int>> graph(size);
for (int from = 0; from < size; ++from) {
for (int to = 0; to < size; ++to) {
if (random() % 8 == 0) graph[from].push_back(to);
}
}
auto actual = m1une::game::retrograde_analysis(graph);
assert(actual.outcome == naive_outcomes(graph));
for (int vertex = 0; vertex < size; ++vertex) {
assert((actual.distance[vertex] == -1)
== (actual.outcome[vertex] == GameOutcome::Draw));
if (actual.outcome[vertex] == GameOutcome::Draw) {
assert(actual.move[vertex] != -1);
assert(actual.outcome[actual.move[vertex]] == GameOutcome::Draw);
} else if (graph[vertex].empty()) {
assert(actual.outcome[vertex] == GameOutcome::Lose);
assert(actual.distance[vertex] == 0);
assert(actual.move[vertex] == -1);
} else {
assert(
std::find(
graph[vertex].begin(),
graph[vertex].end(),
actual.move[vertex]
) != graph[vertex].end()
);
if (actual.outcome[vertex] == GameOutcome::Win) {
assert(
actual.outcome[actual.move[vertex]]
== GameOutcome::Lose
);
int best = size + 1;
for (int next : graph[vertex]) {
if (actual.outcome[next] == GameOutcome::Lose) {
best = std::min(best, actual.distance[next] + 1);
}
}
assert(actual.distance[vertex] == best);
} else {
assert(
actual.outcome[actual.move[vertex]]
== GameOutcome::Win
);
int best = 0;
for (int next : graph[vertex]) {
best = std::max(best, actual.distance[next] + 1);
}
assert(actual.distance[vertex] == best);
}
assert(
actual.distance[vertex]
== actual.distance[actual.move[vertex]] + 1
);
}
}
}
}
std::vector<std::vector<int>> chain(5);
chain[0].push_back(1);
chain[1].push_back(2);
chain[2].push_back(3);
chain[3].push_back(4);
auto result = m1une::game::retrograde_analysis(chain);
for (int vertex = 0; vertex < 5; ++vertex) {
assert(result.distance[vertex] == 4 - vertex);
}
}
} // namespace
int main() {
m1une::utilities::FastInput fast_input;
m1une::utilities::FastOutput fast_output;
test_nim();
test_grundy_random();
test_retrograde_random();
long long first, second;
fast_input >> first >> second;
fast_output << first + second << '\n';
}