m1une's library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:heavy_check_mark: verify/graph/functional_graph.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"

#include "../../graph/functional_graph.hpp"
#include "../../utilities/fast_io.hpp"

#include <cassert>
#include <cstdint>
#include <vector>

namespace {

int naive_jump(
    const std::vector<int>& successor,
    int vertex,
    std::uint64_t steps
) {
    const int n = int(successor.size());
    std::vector<long long> first_visit(n, -1);
    std::vector<int> path;
    while (first_visit[vertex] == -1) {
        first_visit[vertex] = int(path.size());
        path.push_back(vertex);
        vertex = successor[vertex];
    }

    if (steps < path.size()) return path[steps];
    const std::uint64_t cycle_start = std::uint64_t(first_visit[vertex]);
    const std::uint64_t cycle_length = path.size() - cycle_start;
    const std::uint64_t position =
        cycle_start + (steps - cycle_start) % cycle_length;
    return path[position];
}

long long naive_distance(
    const std::vector<int>& successor,
    int from,
    int to
) {
    const int n = int(successor.size());
    std::vector<char> visited(n, false);
    for (int distance = 0; !visited[from]; distance++) {
        if (from == to) return distance;
        visited[from] = true;
        from = successor[from];
    }
    return -1;
}

std::vector<int> naive_orbit(
    const std::vector<int>& successor,
    int vertex
) {
    std::vector<char> visited(successor.size(), false);
    std::vector<int> result;
    while (!visited[vertex]) {
        visited[vertex] = true;
        result.push_back(vertex);
        vertex = successor[vertex];
    }
    return result;
}

std::uint64_t naive_visit_count(
    const std::vector<int>& successor,
    int from,
    int to,
    std::uint64_t step_count
) {
    std::uint64_t result = 0;
    for (std::uint64_t step = 0; step < step_count; step++) {
        if (from == to) result++;
        from = successor[from];
    }
    return result;
}

long long naive_first_meeting_time(
    const std::vector<int>& successor,
    int first,
    int second
) {
    const int n = int(successor.size());
    std::vector<char> visited(n * n, false);
    for (int time = 0; !visited[first * n + second]; time++) {
        if (first == second) return time;
        visited[first * n + second] = true;
        first = successor[first];
        second = successor[second];
    }
    return -1;
}

void test_focused_cases() {
    const std::vector<int> successor = {1, 2, 0, 2, 3, 6, 5, 6, 3};
    m1une::graph::FunctionalGraph graph(successor);

    assert(graph.size() == 9);
    assert(!graph.empty());
    assert(graph.component_count == 2);
    assert(graph.same_component(0, 4));
    assert(!graph.same_component(0, 5));
    assert(graph.on_cycle(0));
    assert(graph.on_cycle(5));
    assert(!graph.on_cycle(4));
    assert(graph.cycle_entry[4] == 2);
    assert(graph.distance_to_cycle[4] == 2);
    assert(graph.cycle_size(4) == 3);
    assert(graph.cycle_size(7) == 2);
    assert(graph.component_size[graph.component[4]] == 6);
    assert(graph.component_size[graph.component[7]] == 3);
    assert((graph.predecessors[3] == std::vector<int>{4, 8}));
    assert(graph.orbit_size(4) == 5);
    assert((graph.orbit(4) == std::vector<int>{4, 3, 2, 0, 1}));

    assert(graph.jump(4, 0) == 4);
    assert(graph.jump(4, 1) == 3);
    assert(graph.jump(4, 2) == 2);
    assert(graph.jump(4, 4) == 1);
    assert(graph.jump(7, 3) == 6);
    assert(graph.jump(4, UINT64_C(1000000000000000000)) ==
           naive_jump(successor, 4, UINT64_C(1000000000000000000)));

    assert(graph.distance(4, 4) == 0);
    assert(graph.distance(4, 3) == 1);
    assert(graph.distance(4, 2) == 2);
    assert(graph.distance(4, 1) == 4);
    assert(graph.distance(1, 4) == -1);
    assert(graph.distance(3, 4) == -1);
    assert(graph.distance(4, 5) == -1);
    assert(graph.distance(7, 5) == 2);
    assert(graph.reachable(4, 1));
    assert(!graph.reachable(1, 4));
    assert((graph.path(4, 1) == std::vector<int>{4, 3, 2, 0, 1}));
    assert(graph.path(1, 4).empty());

    assert(graph.visit_count(4, 2, 0) == 0);
    assert(graph.visit_count(4, 2, 3) == 1);
    assert(graph.visit_count(4, 2, 5) == 1);
    assert(graph.visit_count(4, 2, 6) == 2);
    assert(graph.visit_count(4, 3, UINT64_MAX) == 1);
    assert(graph.visit_count(4, 5, UINT64_MAX) == 0);

    assert(graph.first_meeting_time(4, 8) == 1);
    assert(graph.first_meeting_vertex(4, 8) == 3);
    assert(graph.first_meeting_time(4, 0) == 2);
    assert(graph.first_meeting_vertex(4, 0) == 2);
    assert(graph.first_meeting_time(4, 1) == -1);
    assert(graph.first_meeting_vertex(4, 1) == -1);
    assert(graph.first_meeting_time(7, 5) == 1);
    assert(graph.first_meeting_vertex(7, 5) == 6);
    assert(graph.first_meeting_time(4, 5) == -1);
    assert(graph.first_meeting_time(2, 2) == 0);

    graph.build(std::vector<int>{0});
    assert(graph.size() == 1);
    assert(graph.component_count == 1);
    assert(graph.on_cycle(0));
    assert(graph.jump(0, UINT64_MAX) == 0);
    assert(graph.distance(0, 0) == 0);
    assert(graph.orbit_size(0) == 1);
    assert(graph.visit_count(0, 0, UINT64_MAX) == UINT64_MAX);
    assert(graph.first_meeting_time(0, 0) == 0);

    graph.build(std::vector<int>());
    assert(graph.empty());
    assert(graph.component_count == 0);
    assert(graph.cycles.empty());
}

void test_randomized() {
    std::uint64_t state = UINT64_C(0x5f3759df12345678);
    auto random = [&state]() {
        state ^= state << 7;
        state ^= state >> 9;
        return state;
    };

    for (int trial = 0; trial < 500; trial++) {
        const int n = 1 + int(random() % 60);
        std::vector<int> successor(n);
        for (int& to : successor) to = int(random() % n);
        m1une::graph::FunctionalGraph graph(successor);

        assert(graph.size() == n);
        assert(1 <= graph.component_count && graph.component_count <= n);
        std::vector<int> expected_component_size(graph.component_count, 0);
        for (int component : graph.component) expected_component_size[component]++;
        assert(graph.component_size == expected_component_size);
        int cycle_vertex_count = 0;
        for (int component = 0; component < graph.component_count; component++) {
            const std::vector<int>& cycle = graph.cycles[component];
            assert(!cycle.empty());
            cycle_vertex_count += int(cycle.size());
            for (int position = 0; position < int(cycle.size()); position++) {
                const int vertex = cycle[position];
                const int next = cycle[(position + 1) % cycle.size()];
                assert(successor[vertex] == next);
                assert(graph.component[vertex] == component);
                assert(graph.cycle_entry[vertex] == vertex);
                assert(graph.cycle_position[vertex] == position);
                assert(graph.distance_to_cycle[vertex] == 0);
            }
        }

        int counted_cycle_vertices = 0;
        for (int vertex = 0; vertex < n; vertex++) {
            assert(0 <= graph.component[vertex]);
            assert(graph.component[vertex] < graph.component_count);
            assert(0 <= graph.cycle_position[vertex]);
            assert(graph.cycle_position[vertex] < graph.cycle_size(vertex));
            assert(graph.cycles[graph.component[vertex]][graph.cycle_position[vertex]] ==
                   graph.cycle_entry[vertex]);
            assert(graph.jump(vertex, graph.distance_to_cycle[vertex]) ==
                   graph.cycle_entry[vertex]);
            assert(graph.orbit(vertex) == naive_orbit(successor, vertex));
            assert(graph.orbit_size(vertex) == int(graph.orbit(vertex).size()));
            if (graph.on_cycle(vertex)) counted_cycle_vertices++;

            int predecessor_count = 0;
            for (int from = 0; from < n; from++) {
                if (successor[from] == vertex) predecessor_count++;
            }
            assert(int(graph.predecessors[vertex].size()) == predecessor_count);
            for (int from : graph.predecessors[vertex]) {
                assert(successor[from] == vertex);
            }

            for (int query = 0; query < 12; query++) {
                const std::uint64_t steps =
                    query == 0 ? random() : random() % std::uint64_t(4 * n + 1);
                assert(graph.jump(vertex, steps) == naive_jump(successor, vertex, steps));
            }
            for (int query = 0; query < 8; query++) {
                const int to = int(random() % n);
                const std::uint64_t step_count = random() % std::uint64_t(4 * n + 1);
                assert(graph.visit_count(vertex, to, step_count) ==
                       naive_visit_count(successor, vertex, to, step_count));
            }
        }
        assert(counted_cycle_vertices == cycle_vertex_count);

        for (int from = 0; from < n; from++) {
            for (int to = 0; to < n; to++) {
                const long long expected_distance = naive_distance(successor, from, to);
                assert(graph.distance(from, to) == expected_distance);
                assert(graph.reachable(from, to) == (expected_distance != -1));
                const std::vector<int> path = graph.path(from, to);
                if (expected_distance == -1) {
                    assert(path.empty());
                } else {
                    assert(int(path.size()) == expected_distance + 1);
                    int vertex = from;
                    for (int value : path) {
                        assert(value == vertex);
                        vertex = successor[vertex];
                    }
                    assert(path.back() == to);
                }
            }
        }

        for (int query = 0; query < 40; query++) {
            const int first = int(random() % n);
            const int second = int(random() % n);
            const long long expected =
                naive_first_meeting_time(successor, first, second);
            assert(graph.first_meeting_time(first, second) == expected);
            assert(graph.first_meeting_time(second, first) == expected);
            const int meeting_vertex = graph.first_meeting_vertex(first, second);
            assert(meeting_vertex ==
                   (expected == -1 ? -1 : naive_jump(successor, first, expected)));
        }
    }
}

}  // namespace

int main() {
    test_focused_cases();
    test_randomized();

    m1une::utilities::FastInput fast_input;
    m1une::utilities::FastOutput fast_output;
    long long first, second;
    fast_input >> first >> second;
    fast_output << first + second << '\n';
}
#line 1 "verify/graph/functional_graph.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/aplusb"

#line 1 "graph/functional_graph.hpp"



#include <algorithm>
#include <cassert>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>

namespace m1une {
namespace graph {

struct FunctionalGraph {
    int component_count;
    std::vector<int> successor;
    std::vector<std::vector<int>> predecessors;
    std::vector<std::vector<int>> cycles;
    std::vector<int> component;
    std::vector<int> component_size;
    std::vector<int> cycle_entry;
    std::vector<int> cycle_position;
    std::vector<int> distance_to_cycle;

   private:
    std::vector<std::vector<int>> _up;

    void check_vertex(int vertex) const {
        assert(0 <= vertex && vertex < size());
    }

    int advance_before_cycle(int vertex, int steps) const {
        assert(0 <= steps && steps <= distance_to_cycle[vertex]);
        int bit = 0;
        while (steps > 0) {
            if (steps & 1) vertex = _up[bit][vertex];
            steps >>= 1;
            bit++;
        }
        return vertex;
    }

   public:
    FunctionalGraph() : component_count(0) {}

    explicit FunctionalGraph(const std::vector<int>& successor_) {
        build(successor_);
    }

    void build(const std::vector<int>& successor_) {
        successor = successor_;
        const int n = size();
        for (int to : successor) assert(0 <= to && to < n);

        component_count = 0;
        predecessors.assign(n, {});
        cycles.clear();
        component.assign(n, -1);
        cycle_entry.assign(n, -1);
        cycle_position.assign(n, -1);
        distance_to_cycle.assign(n, -1);

        std::vector<int> indegree(n, 0);
        for (int vertex = 0; vertex < n; vertex++) {
            predecessors[successor[vertex]].push_back(vertex);
            indegree[successor[vertex]]++;
        }

        std::queue<int> queue;
        std::vector<char> removed(n, false);
        for (int vertex = 0; vertex < n; vertex++) {
            if (indegree[vertex] == 0) queue.push(vertex);
        }
        while (!queue.empty()) {
            const int vertex = queue.front();
            queue.pop();
            removed[vertex] = true;
            const int to = successor[vertex];
            indegree[to]--;
            if (indegree[to] == 0) queue.push(to);
        }

        for (int start = 0; start < n; start++) {
            if (removed[start] || component[start] != -1) continue;
            const int component_id = int(cycles.size());
            std::vector<int> cycle;
            int vertex = start;
            do {
                const int position = int(cycle.size());
                cycle.push_back(vertex);
                component[vertex] = component_id;
                cycle_entry[vertex] = vertex;
                cycle_position[vertex] = position;
                distance_to_cycle[vertex] = 0;
                vertex = successor[vertex];
            } while (vertex != start);
            cycles.push_back(std::move(cycle));
        }
        component_count = int(cycles.size());

        for (const std::vector<int>& cycle : cycles) {
            for (int vertex : cycle) queue.push(vertex);
        }
        while (!queue.empty()) {
            const int vertex = queue.front();
            queue.pop();
            for (int from : predecessors[vertex]) {
                if (component[from] != -1) continue;
                component[from] = component[vertex];
                cycle_entry[from] = cycle_entry[vertex];
                cycle_position[from] = cycle_position[vertex];
                distance_to_cycle[from] = distance_to_cycle[vertex] + 1;
                queue.push(from);
            }
        }

        component_size.assign(component_count, 0);
        for (int component_id : component) component_size[component_id]++;

        int log = 1;
        while ((std::uint64_t(1) << log) <= std::uint64_t(n)) log++;
        _up.assign(log, successor);
        for (int bit = 1; bit < log; bit++) {
            for (int vertex = 0; vertex < n; vertex++) {
                _up[bit][vertex] = _up[bit - 1][_up[bit - 1][vertex]];
            }
        }
    }

    int size() const {
        return int(successor.size());
    }

    bool empty() const {
        return successor.empty();
    }

    bool same_component(int first, int second) const {
        check_vertex(first);
        check_vertex(second);
        return component[first] == component[second];
    }

    bool on_cycle(int vertex) const {
        check_vertex(vertex);
        return distance_to_cycle[vertex] == 0;
    }

    int cycle_size(int vertex) const {
        check_vertex(vertex);
        return int(cycles[component[vertex]].size());
    }

    int orbit_size(int vertex) const {
        check_vertex(vertex);
        return distance_to_cycle[vertex] + cycle_size(vertex);
    }

    int jump(int vertex, std::uint64_t steps) const {
        check_vertex(vertex);
        const int tail_length = distance_to_cycle[vertex];
        if (steps < std::uint64_t(tail_length)) {
            return advance_before_cycle(vertex, int(steps));
        }

        steps -= std::uint64_t(tail_length);
        const int entry = cycle_entry[vertex];
        const int length = cycle_size(entry);
        const int offset = int(steps % std::uint64_t(length));
        const int position = (cycle_position[entry] + offset) % length;
        return cycles[component[vertex]][position];
    }

    long long distance(int from, int to) const {
        check_vertex(from);
        check_vertex(to);
        if (!same_component(from, to)) return -1;

        if (!on_cycle(to)) {
            if (distance_to_cycle[from] < distance_to_cycle[to]) return -1;
            const int difference = distance_to_cycle[from] - distance_to_cycle[to];
            return advance_before_cycle(from, difference) == to ? difference : -1;
        }

        const int entry = cycle_entry[from];
        const int length = cycle_size(from);
        int cycle_distance = cycle_position[to] - cycle_position[entry];
        if (cycle_distance < 0) cycle_distance += length;
        return static_cast<long long>(distance_to_cycle[from]) + cycle_distance;
    }

    bool reachable(int from, int to) const {
        return distance(from, to) != -1;
    }

    std::vector<int> path(int from, int to) const {
        const long long path_length = distance(from, to);
        if (path_length == -1) return {};

        std::vector<int> result;
        result.reserve(path_length + 1);
        for (long long step = 0; step <= path_length; step++) {
            result.push_back(from);
            from = successor[from];
        }
        return result;
    }

    std::vector<int> orbit(int vertex) const {
        check_vertex(vertex);
        const int length = orbit_size(vertex);
        std::vector<int> result;
        result.reserve(length);
        for (int step = 0; step < length; step++) {
            result.push_back(vertex);
            vertex = successor[vertex];
        }
        return result;
    }

    std::uint64_t visit_count(
        int from,
        int to,
        std::uint64_t step_count
    ) const {
        const long long first_visit = distance(from, to);
        if (first_visit == -1 ||
            std::uint64_t(first_visit) >= step_count) {
            return 0;
        }
        if (!on_cycle(to)) return 1;

        const std::uint64_t remaining =
            step_count - 1 - std::uint64_t(first_visit);
        return 1 + remaining / std::uint64_t(cycle_size(to));
    }

    long long first_meeting_time(int first, int second) const {
        check_vertex(first);
        check_vertex(second);
        if (!same_component(first, second)) return -1;
        if (first == second) return 0;

        const int first_depth = distance_to_cycle[first];
        const int second_depth = distance_to_cycle[second];
        if (first_depth == second_depth &&
            cycle_entry[first] == cycle_entry[second]) {
            int elapsed = 0;
            for (int bit = int(_up.size()) - 1; bit >= 0; bit--) {
                const int steps = 1 << bit;
                if (first_depth - elapsed < steps) continue;
                const int next_first = _up[bit][first];
                const int next_second = _up[bit][second];
                if (next_first == next_second) continue;
                first = next_first;
                second = next_second;
                elapsed += steps;
            }
            return elapsed + 1;
        }

        const int length = cycle_size(first);
        int first_phase =
            cycle_position[first] - first_depth % length;
        int second_phase =
            cycle_position[second] - second_depth % length;
        if (first_phase < 0) first_phase += length;
        if (second_phase < 0) second_phase += length;
        if (first_phase != second_phase) return -1;
        return std::max(first_depth, second_depth);
    }

    int first_meeting_vertex(int first, int second) const {
        const long long time = first_meeting_time(first, second);
        if (time == -1) return -1;
        return jump(first, std::uint64_t(time));
    }
};

}  // namespace graph
}  // namespace m1une


#line 1 "utilities/fast_io.hpp"



#line 5 "utilities/fast_io.hpp"
#include <array>
#include <cerrno>
#include <charconv>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#line 12 "utilities/fast_io.hpp"
#include <cstring>
#include <iterator>
#include <string>
#include <sys/stat.h>
#include <type_traits>
#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 5 "verify/graph/functional_graph.test.cpp"

#line 9 "verify/graph/functional_graph.test.cpp"

namespace {

int naive_jump(
    const std::vector<int>& successor,
    int vertex,
    std::uint64_t steps
) {
    const int n = int(successor.size());
    std::vector<long long> first_visit(n, -1);
    std::vector<int> path;
    while (first_visit[vertex] == -1) {
        first_visit[vertex] = int(path.size());
        path.push_back(vertex);
        vertex = successor[vertex];
    }

    if (steps < path.size()) return path[steps];
    const std::uint64_t cycle_start = std::uint64_t(first_visit[vertex]);
    const std::uint64_t cycle_length = path.size() - cycle_start;
    const std::uint64_t position =
        cycle_start + (steps - cycle_start) % cycle_length;
    return path[position];
}

long long naive_distance(
    const std::vector<int>& successor,
    int from,
    int to
) {
    const int n = int(successor.size());
    std::vector<char> visited(n, false);
    for (int distance = 0; !visited[from]; distance++) {
        if (from == to) return distance;
        visited[from] = true;
        from = successor[from];
    }
    return -1;
}

std::vector<int> naive_orbit(
    const std::vector<int>& successor,
    int vertex
) {
    std::vector<char> visited(successor.size(), false);
    std::vector<int> result;
    while (!visited[vertex]) {
        visited[vertex] = true;
        result.push_back(vertex);
        vertex = successor[vertex];
    }
    return result;
}

std::uint64_t naive_visit_count(
    const std::vector<int>& successor,
    int from,
    int to,
    std::uint64_t step_count
) {
    std::uint64_t result = 0;
    for (std::uint64_t step = 0; step < step_count; step++) {
        if (from == to) result++;
        from = successor[from];
    }
    return result;
}

long long naive_first_meeting_time(
    const std::vector<int>& successor,
    int first,
    int second
) {
    const int n = int(successor.size());
    std::vector<char> visited(n * n, false);
    for (int time = 0; !visited[first * n + second]; time++) {
        if (first == second) return time;
        visited[first * n + second] = true;
        first = successor[first];
        second = successor[second];
    }
    return -1;
}

void test_focused_cases() {
    const std::vector<int> successor = {1, 2, 0, 2, 3, 6, 5, 6, 3};
    m1une::graph::FunctionalGraph graph(successor);

    assert(graph.size() == 9);
    assert(!graph.empty());
    assert(graph.component_count == 2);
    assert(graph.same_component(0, 4));
    assert(!graph.same_component(0, 5));
    assert(graph.on_cycle(0));
    assert(graph.on_cycle(5));
    assert(!graph.on_cycle(4));
    assert(graph.cycle_entry[4] == 2);
    assert(graph.distance_to_cycle[4] == 2);
    assert(graph.cycle_size(4) == 3);
    assert(graph.cycle_size(7) == 2);
    assert(graph.component_size[graph.component[4]] == 6);
    assert(graph.component_size[graph.component[7]] == 3);
    assert((graph.predecessors[3] == std::vector<int>{4, 8}));
    assert(graph.orbit_size(4) == 5);
    assert((graph.orbit(4) == std::vector<int>{4, 3, 2, 0, 1}));

    assert(graph.jump(4, 0) == 4);
    assert(graph.jump(4, 1) == 3);
    assert(graph.jump(4, 2) == 2);
    assert(graph.jump(4, 4) == 1);
    assert(graph.jump(7, 3) == 6);
    assert(graph.jump(4, UINT64_C(1000000000000000000)) ==
           naive_jump(successor, 4, UINT64_C(1000000000000000000)));

    assert(graph.distance(4, 4) == 0);
    assert(graph.distance(4, 3) == 1);
    assert(graph.distance(4, 2) == 2);
    assert(graph.distance(4, 1) == 4);
    assert(graph.distance(1, 4) == -1);
    assert(graph.distance(3, 4) == -1);
    assert(graph.distance(4, 5) == -1);
    assert(graph.distance(7, 5) == 2);
    assert(graph.reachable(4, 1));
    assert(!graph.reachable(1, 4));
    assert((graph.path(4, 1) == std::vector<int>{4, 3, 2, 0, 1}));
    assert(graph.path(1, 4).empty());

    assert(graph.visit_count(4, 2, 0) == 0);
    assert(graph.visit_count(4, 2, 3) == 1);
    assert(graph.visit_count(4, 2, 5) == 1);
    assert(graph.visit_count(4, 2, 6) == 2);
    assert(graph.visit_count(4, 3, UINT64_MAX) == 1);
    assert(graph.visit_count(4, 5, UINT64_MAX) == 0);

    assert(graph.first_meeting_time(4, 8) == 1);
    assert(graph.first_meeting_vertex(4, 8) == 3);
    assert(graph.first_meeting_time(4, 0) == 2);
    assert(graph.first_meeting_vertex(4, 0) == 2);
    assert(graph.first_meeting_time(4, 1) == -1);
    assert(graph.first_meeting_vertex(4, 1) == -1);
    assert(graph.first_meeting_time(7, 5) == 1);
    assert(graph.first_meeting_vertex(7, 5) == 6);
    assert(graph.first_meeting_time(4, 5) == -1);
    assert(graph.first_meeting_time(2, 2) == 0);

    graph.build(std::vector<int>{0});
    assert(graph.size() == 1);
    assert(graph.component_count == 1);
    assert(graph.on_cycle(0));
    assert(graph.jump(0, UINT64_MAX) == 0);
    assert(graph.distance(0, 0) == 0);
    assert(graph.orbit_size(0) == 1);
    assert(graph.visit_count(0, 0, UINT64_MAX) == UINT64_MAX);
    assert(graph.first_meeting_time(0, 0) == 0);

    graph.build(std::vector<int>());
    assert(graph.empty());
    assert(graph.component_count == 0);
    assert(graph.cycles.empty());
}

void test_randomized() {
    std::uint64_t state = UINT64_C(0x5f3759df12345678);
    auto random = [&state]() {
        state ^= state << 7;
        state ^= state >> 9;
        return state;
    };

    for (int trial = 0; trial < 500; trial++) {
        const int n = 1 + int(random() % 60);
        std::vector<int> successor(n);
        for (int& to : successor) to = int(random() % n);
        m1une::graph::FunctionalGraph graph(successor);

        assert(graph.size() == n);
        assert(1 <= graph.component_count && graph.component_count <= n);
        std::vector<int> expected_component_size(graph.component_count, 0);
        for (int component : graph.component) expected_component_size[component]++;
        assert(graph.component_size == expected_component_size);
        int cycle_vertex_count = 0;
        for (int component = 0; component < graph.component_count; component++) {
            const std::vector<int>& cycle = graph.cycles[component];
            assert(!cycle.empty());
            cycle_vertex_count += int(cycle.size());
            for (int position = 0; position < int(cycle.size()); position++) {
                const int vertex = cycle[position];
                const int next = cycle[(position + 1) % cycle.size()];
                assert(successor[vertex] == next);
                assert(graph.component[vertex] == component);
                assert(graph.cycle_entry[vertex] == vertex);
                assert(graph.cycle_position[vertex] == position);
                assert(graph.distance_to_cycle[vertex] == 0);
            }
        }

        int counted_cycle_vertices = 0;
        for (int vertex = 0; vertex < n; vertex++) {
            assert(0 <= graph.component[vertex]);
            assert(graph.component[vertex] < graph.component_count);
            assert(0 <= graph.cycle_position[vertex]);
            assert(graph.cycle_position[vertex] < graph.cycle_size(vertex));
            assert(graph.cycles[graph.component[vertex]][graph.cycle_position[vertex]] ==
                   graph.cycle_entry[vertex]);
            assert(graph.jump(vertex, graph.distance_to_cycle[vertex]) ==
                   graph.cycle_entry[vertex]);
            assert(graph.orbit(vertex) == naive_orbit(successor, vertex));
            assert(graph.orbit_size(vertex) == int(graph.orbit(vertex).size()));
            if (graph.on_cycle(vertex)) counted_cycle_vertices++;

            int predecessor_count = 0;
            for (int from = 0; from < n; from++) {
                if (successor[from] == vertex) predecessor_count++;
            }
            assert(int(graph.predecessors[vertex].size()) == predecessor_count);
            for (int from : graph.predecessors[vertex]) {
                assert(successor[from] == vertex);
            }

            for (int query = 0; query < 12; query++) {
                const std::uint64_t steps =
                    query == 0 ? random() : random() % std::uint64_t(4 * n + 1);
                assert(graph.jump(vertex, steps) == naive_jump(successor, vertex, steps));
            }
            for (int query = 0; query < 8; query++) {
                const int to = int(random() % n);
                const std::uint64_t step_count = random() % std::uint64_t(4 * n + 1);
                assert(graph.visit_count(vertex, to, step_count) ==
                       naive_visit_count(successor, vertex, to, step_count));
            }
        }
        assert(counted_cycle_vertices == cycle_vertex_count);

        for (int from = 0; from < n; from++) {
            for (int to = 0; to < n; to++) {
                const long long expected_distance = naive_distance(successor, from, to);
                assert(graph.distance(from, to) == expected_distance);
                assert(graph.reachable(from, to) == (expected_distance != -1));
                const std::vector<int> path = graph.path(from, to);
                if (expected_distance == -1) {
                    assert(path.empty());
                } else {
                    assert(int(path.size()) == expected_distance + 1);
                    int vertex = from;
                    for (int value : path) {
                        assert(value == vertex);
                        vertex = successor[vertex];
                    }
                    assert(path.back() == to);
                }
            }
        }

        for (int query = 0; query < 40; query++) {
            const int first = int(random() % n);
            const int second = int(random() % n);
            const long long expected =
                naive_first_meeting_time(successor, first, second);
            assert(graph.first_meeting_time(first, second) == expected);
            assert(graph.first_meeting_time(second, first) == expected);
            const int meeting_vertex = graph.first_meeting_vertex(first, second);
            assert(meeting_vertex ==
                   (expected == -1 ? -1 : naive_jump(successor, first, expected)));
        }
    }
}

}  // namespace

int main() {
    test_focused_cases();
    test_randomized();

    m1une::utilities::FastInput fast_input;
    m1une::utilities::FastOutput fast_output;
    long long first, second;
    fast_input >> first >> second;
    fast_output << first + second << '\n';
}
Back to top page