Library

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

View the Project on GitHub ebi-fly13/Library

:heavy_check_mark: Subtree Hash
(tree/subtree_hash.hpp)

説明

get(v)

根を $v$ としたときの根付き木のハッシュを返す。

get(v, root)

根が $root$ であるときの頂点 $v$ の部分木のハッシュを返す。

Depends on

Required by

Verified with

Code

#pragma once

#include <vector>

#include "../graph/base.hpp"
#include "../modint/modint61.hpp"
#include "../tree/rerooting.hpp"
#include "../utility/random_number_generator.hpp"

namespace ebi {

template <class T> struct subtree_hash {
  private:
    using V = std::pair<int, modint61>;

    static modint61 hash_base(int k) {
        static std::vector<modint61> r;
        static random_number_generator rng;
        while ((int)r.size() <= k) {
            r.emplace_back(rng.get<std::uint64_t>(0, modint61::mod()));
        }
        return r[k];
    }

    static auto merge() {
        return [&](V a, V b) -> V {
            return {std::max(a.first, b.first), a.second * b.second};
        };
    }

    static auto put_edge() {
        return [&](Graph<T>::edge_type, V a) -> V {
            return {a.first + 1, a.second};
        };
    }

    static auto put_root() {
        return [&](int, V a) -> V {
            return {a.first, a.second + hash_base(a.first)};
        };
    }

  public:
    subtree_hash(const Graph<T> &tree)
        : dp(tree, V{0, 1}, merge(), put_edge(), put_root()) {}

    modint61 get(int v) const {
        return dp.get(v).second;
    }

    modint61 get(int v, int root) {
        return dp.get(v, root).second;
    }

  private:
    rerooting_dp<T, V> dp;
};

}  // namespace ebi
#line 2 "tree/subtree_hash.hpp"

#include <vector>

#line 2 "graph/base.hpp"

#include <cassert>
#include <iostream>
#include <ranges>
#line 7 "graph/base.hpp"

#line 2 "data_structure/simple_csr.hpp"

#line 4 "data_structure/simple_csr.hpp"
#include <utility>
#line 6 "data_structure/simple_csr.hpp"

namespace ebi {

template <class E> struct simple_csr {
    simple_csr() = default;

    simple_csr(int n, const std::vector<std::pair<int, E>>& elements)
        : start(n + 1, 0), elist(elements.size()) {
        for (auto e : elements) {
            start[e.first + 1]++;
        }
        for (auto i : std::views::iota(0, n)) {
            start[i + 1] += start[i];
        }
        auto counter = start;
        for (auto [i, e] : elements) {
            elist[counter[i]++] = e;
        }
    }

    simple_csr(const std::vector<std::vector<E>>& es)
        : start(es.size() + 1, 0) {
        int n = es.size();
        for (auto i : std::views::iota(0, n)) {
            start[i + 1] = (int)es[i].size() + start[i];
        }
        elist.resize(start.back());
        for (auto i : std::views::iota(0, n)) {
            std::copy(es[i].begin(), es[i].end(), elist.begin() + start[i]);
        }
    }

    int size() const {
        return (int)start.size() - 1;
    }

    const auto operator[](int i) const {
        return std::ranges::subrange(elist.begin() + start[i],
                                     elist.begin() + start[i + 1]);
    }
    auto operator[](int i) {
        return std::ranges::subrange(elist.begin() + start[i],
                                     elist.begin() + start[i + 1]);
    }

    const auto operator()(int i, int l, int r) const {
        return std::ranges::subrange(elist.begin() + start[i] + l,
                                     elist.begin() + start[i + 1] + r);
    }
    auto operator()(int i, int l, int r) {
        return std::ranges::subrange(elist.begin() + start[i] + l,
                                     elist.begin() + start[i + 1] + r);
    }

  private:
    std::vector<int> start;
    std::vector<E> elist;
};

}  // namespace ebi
#line 9 "graph/base.hpp"

namespace ebi {

template <class T> struct Edge {
    int from, to;
    T cost;
    int id;
};

template <class E> struct Graph {
    using cost_type = E;
    using edge_type = Edge<cost_type>;

    Graph(int n_) : n(n_) {}

    Graph() = default;

    void add_edge(int u, int v, cost_type c) {
        assert(!prepared && u < n && v < n);
        buff.emplace_back(u, edge_type{u, v, c, m});
        edges.emplace_back(edge_type{u, v, c, m++});
    }

    void add_undirected_edge(int u, int v, cost_type c) {
        assert(!prepared && u < n && v < n);
        buff.emplace_back(u, edge_type{u, v, c, m});
        buff.emplace_back(v, edge_type{v, u, c, m});
        edges.emplace_back(edge_type{u, v, c, m});
        m++;
    }

    void read_tree(int offset = 1, bool is_weighted = false) {
        read_graph(n - 1, offset, false, is_weighted);
    }

    void read_parents(int offset = 1) {
        for (auto i : std::views::iota(1, n)) {
            int p;
            std::cin >> p;
            p -= offset;
            add_undirected_edge(p, i, 1);
        }
        build();
    }

    void read_graph(int e, int offset = 1, bool is_directed = false,
                    bool is_weighted = false) {
        for (int i = 0; i < e; i++) {
            int u, v;
            std::cin >> u >> v;
            u -= offset;
            v -= offset;
            if (is_weighted) {
                cost_type c;
                std::cin >> c;
                if (is_directed) {
                    add_edge(u, v, c);
                } else {
                    add_undirected_edge(u, v, c);
                }
            } else {
                if (is_directed) {
                    add_edge(u, v, 1);
                } else {
                    add_undirected_edge(u, v, 1);
                }
            }
        }
        build();
    }

    void build() {
        assert(!prepared);
        csr = simple_csr<edge_type>(n, buff);
        buff.clear();
        prepared = true;
    }

    int size() const {
        return n;
    }

    int node_number() const {
        return n;
    }

    int edge_number() const {
        return m;
    }

    edge_type get_edge(int i) const {
        assert(prepared);
        return edges[i];
    }

    std::vector<edge_type> get_edges() const {
        assert(prepared);
        return edges;
    }

    const auto operator[](int i) const {
        assert(prepared);
        return csr[i];
    }
    auto operator[](int i) {
        assert(prepared);
        return csr[i];
    }

  private:
    int n, m = 0;

    std::vector<std::pair<int, edge_type>> buff;

    std::vector<edge_type> edges;
    simple_csr<edge_type> csr;
    bool prepared = false;
};

}  // namespace ebi
#line 2 "modint/modint61.hpp"

#line 4 "modint/modint61.hpp"
#include <cstdint>
#line 6 "modint/modint61.hpp"

#line 2 "modint/base.hpp"

#include <concepts>
#line 6 "modint/base.hpp"

namespace ebi {

template <class T>
concept Modint = requires(T a, T b) {
    a + b;
    a - b;
    a * b;
    a / b;
    a.inv();
    a.val();
    a.pow(std::declval<long long>());
    T::mod();
};

template <Modint mint> std::istream &operator>>(std::istream &os, mint &a) {
    long long x;
    os >> x;
    a = x;
    return os;
}

template <Modint mint>
std::ostream &operator<<(std::ostream &os, const mint &a) {
    return os << a.val();
}

}  // namespace ebi
#line 8 "modint/modint61.hpp"

namespace ebi {

struct modint61 {
  private:
    using mint = modint61;
    using u64 = std::uint64_t;
    constexpr static u64 m = (1ull << 61) - 1;
    constexpr static u64 MASK31 = (1ull << 31) - 1;
    constexpr static u64 MASK30 = (1ull << 30) - 1;

  public:
    constexpr static u64 mod() {
        return m;
    }

    constexpr modint61() : _v(0) {}

    constexpr modint61(long long v) {
        v %= (long long)umod();
        if (v < 0) v += (long long)umod();
        _v = u64(v);
    }

    constexpr u64 val() const {
        return _v;
    }

    constexpr u64 value() const {
        return val();
    }

    constexpr mint &operator++() {
        _v++;
        if (_v == umod()) _v = 0;
        return *this;
    }

    constexpr mint &operator--() {
        if (_v == 0) _v = umod();
        _v--;
        return *this;
    }

    constexpr mint &operator+=(const mint &rhs) {
        _v += rhs._v;
        _v = safe_mod(_v);
        return *this;
    }

    constexpr mint &operator-=(const mint &rhs) {
        if (_v < rhs._v) _v += umod();
        assert(_v >= rhs._v);
        _v -= rhs._v;
        return *this;
    }

    constexpr mint &operator*=(const mint &rhs) {
        u64 au = _v >> 31, ad = _v & MASK31;
        u64 bu = rhs._v >> 31, bd = rhs._v & MASK31;
        u64 mid = ad * bu + au * bd;
        u64 midu = mid >> 30;
        u64 midd = mid & MASK30;
        _v = (au * bu * 2 + midu + (midd << 31) + ad * bd);
        _v = safe_mod(_v);
        return *this;
    }

    constexpr mint &operator/=(const mint &rhs) {
        return *this *= rhs.inv();
    }

    constexpr mint pow(long long n) const {
        assert(0 <= n);
        mint x = *this, res = 1;
        while (n) {
            if (n & 1) res *= x;
            x *= x;
            n >>= 1;
        }
        return res;
    }

    constexpr mint inv() const {
        assert(_v);
        return pow(umod() - 2);
    }

    friend mint operator+(const mint &lhs, const mint &rhs) {
        return mint(lhs) += rhs;
    }
    friend mint operator-(const mint &lhs, const mint &rhs) {
        return mint(lhs) -= rhs;
    }
    friend mint operator*(const mint &lhs, const mint &rhs) {
        return mint(lhs) *= rhs;
    }
    friend mint operator/(const mint &lhs, const mint &rhs) {
        return mint(lhs) /= rhs;
    }
    friend bool operator==(const mint &lhs, const mint &rhs) {
        return lhs.val() == rhs.val();
    }
    friend bool operator!=(const mint &lhs, const mint &rhs) {
        return !(lhs == rhs);
    }
    friend bool operator<(const mint &lhs, const mint &rhs) {
        return lhs._v < rhs._v;
    }
    friend bool operator>(const mint &lhs, const mint &rhs) {
        return rhs < lhs;
    }

  private:
    u64 _v = 0;

    constexpr static u64 umod() {
        return m;
    }

    constexpr u64 safe_mod(const u64 &a) {
        u64 au = a >> 61;
        u64 ad = a & umod();
        u64 res = au + ad;
        if (res >= umod()) res -= umod();
        return res;
    }
};

}  // namespace ebi
#line 2 "tree/rerooting.hpp"

#line 6 "tree/rerooting.hpp"

#line 2 "tree/heavy_light_decomposition.hpp"

#include <algorithm>
#line 6 "tree/heavy_light_decomposition.hpp"

#line 8 "tree/heavy_light_decomposition.hpp"

namespace ebi {

template <class T> struct heavy_light_decomposition {
  private:
    void dfs_sz(int v) {
        for (auto &e : g[v]) {
            if (e.to == par[v]) continue;
            par[e.to] = v;
            depth_[e.to] = depth_[v] + 1;
            dist[e.to] = dist[v] + e.cost;
            dfs_sz(e.to);
            sz[v] += sz[e.to];
            if (sz[e.to] > sz[g[v][0].to] || g[v][0].to == par[v])
                std::swap(e, g[v][0]);
        }
    }

    void dfs_hld(int v) {
        in[v] = num++;
        rev[in[v]] = v;
        for (auto e : g[v]) {
            if (e.to == par[v]) continue;
            nxt[e.to] = (e.to == g[v][0].to ? nxt[v] : e.to);
            dfs_hld(e.to);
        }
        out[v] = num;
    }

    // [u, v) パスの取得 (v は u の祖先)
    std::vector<std::pair<int, int>> ascend(int u, int v) const {
        std::vector<std::pair<int, int>> res;
        while (nxt[u] != nxt[v]) {
            res.emplace_back(in[u], in[nxt[u]]);
            u = par[nxt[u]];
        }
        if (u != v) res.emplace_back(in[u], in[v] + 1);
        return res;
    }

    // (u, v] パスの取得 (u は v の祖先)
    std::vector<std::pair<int, int>> descend(int u, int v) const {
        if (u == v) return {};
        if (nxt[u] == nxt[v]) return {{in[u] + 1, in[v]}};
        auto res = descend(u, par[nxt[v]]);
        res.emplace_back(in[nxt[v]], in[v]);
        return res;
    }

  public:
    heavy_light_decomposition(const Graph<T> &gh, int root_ = 0)
        : n(gh.size()),
          root(root_),
          g(gh),
          sz(n, 1),
          in(n),
          out(n),
          nxt(n),
          par(n, -1),
          depth_(n, 0),
          rev(n),
          dist(n, 0) {
        nxt[root] = root;
        dfs_sz(root);
        dfs_hld(root);
    }

    int idx(int u) const {
        return in[u];
    }

    int rev_idx(int i) const {
        return rev[i];
    }

    int la(int v, int k) const {
        while (1) {
            int u = nxt[v];
            if (in[u] <= in[v] - k) return rev[in[v] - k];
            k -= in[v] - in[u] + 1;
            v = par[u];
        }
    }

    int lca(int u, int v) const {
        while (nxt[u] != nxt[v]) {
            if (in[u] < in[v]) std::swap(u, v);
            u = par[nxt[u]];
        }
        return depth_[u] < depth_[v] ? u : v;
    }

    int jump(int s, int t, int i) const {
        if (i == 0) return s;
        int l = lca(s, t);
        int d = depth_[s] + depth_[t] - depth_[l] * 2;
        if (d < i) return -1;
        if (depth_[s] - depth_[l] >= i) return la(s, i);
        i = d - i;
        return la(t, i);
    }

    std::vector<int> path(int s, int t) const {
        int l = lca(s, t);
        std::vector<int> a, b;
        for (; s != l; s = par[s]) a.emplace_back(s);
        for (; t != l; t = par[t]) b.emplace_back(t);
        a.emplace_back(l);
        std::reverse(b.begin(), b.end());
        a.insert(a.end(), b.begin(), b.end());
        return a;
    }

    int root_of_heavy_path(int u) const {
        return nxt[u];
    }

    int parent(int u) const {
        return par[u];
    }

    T distance(int u, int v) const {
        return dist[u] + dist[v] - 2 * dist[lca(u, v)];
    }

    T distance_from_root(int v) const {
        return dist[v];
    }

    T depth(int v) const {
        return depth_[v];
    }

    bool at_path(int u, int v, int s) const {
        return distance(u, v) == distance(u, s) + distance(s, v);
    }

    std::pair<int, int> subtree_section(int v) const {
        return {in[v], out[v]};
    }

    bool is_subtree(int u, int v) const {
        return in[u] <= in[v] && in[v] < out[u];
    }

    template <class F>
    void path_noncommutative_query(int u, int v, bool vertex,
                                   const F &f) const {
        int l = lca(u, v);
        for (auto [a, b] : ascend(u, l)) f(a + 1, b);
        if (vertex) f(in[l], in[l] + 1);
        for (auto [a, b] : descend(l, v)) f(a, b + 1);
    }

    std::vector<std::pair<int, int>> path_sections(int u, int v,
                                                   bool vertex) const {
        int l = lca(u, v);
        std::vector<std::pair<int, int>> sections;
        for (auto [a, b] : ascend(u, l)) sections.emplace_back(a + 1, b);
        if (vertex) sections.emplace_back(in[l], in[l] + 1);
        for (auto [a, b] : descend(l, v)) sections.emplace_back(a, b + 1);
        return sections;
    }

    template <class F>
    int max_path(int u, int v, bool vertex, F binary_search) const {
        int prev = -1;
        int l = lca(u, v);
        for (auto [a, b] : ascend(u, l)) {
            a++;
            int m = binary_search(a, b);
            if (m == b) {
                prev = rev[b];
            } else {
                return (m == a ? prev : rev[m]);
            }
        }
        if (vertex) {
            int m = binary_search(in[l], in[l] + 1);
            if (m == in[l]) {
                return prev;
            } else {
                prev = l;
            }
        }
        for (auto [a, b] : descend(l, v)) {
            b++;
            int m = binary_search(a, b);
            if (m == b) {
                prev = rev[b - 1];
            } else {
                return m == a ? prev : rev[m - 1];
            }
        }
        return v;
    }

    template <class F> void subtree_query(int u, bool vertex, const F &f) {
        f(in[u] + int(!vertex), out[u]);
    }

    const std::vector<int> &dfs_order() const {
        return rev;
    }

    template <class ADD, class QUERY, class CLEAR, class RESET>
    void dsu_on_tree(const ADD &add, const QUERY &query, const CLEAR &clear,
                     const RESET &reset) const;

    std::vector<std::pair<int, int>> lca_based_auxiliary_tree_dfs_order(
        std::vector<int> vs) const;

    std::pair<std::vector<int>, Graph<T>> lca_based_auxiliary_tree(
        std::vector<int> vs) const;

  private:
    int n, root;
    Graph<T> g;
    std::vector<int> sz, in, out, nxt, par, depth_, rev;
    std::vector<T> dist;

    int num = 0;
};

}  // namespace ebi
#line 9 "tree/rerooting.hpp"

namespace ebi {

template <class T, class V> struct rerooting_dp {
    template <class MERGE, class PUT_EDGE, class PUT_ROOT>
    rerooting_dp(const Graph<T> &tree, const V e, const MERGE &merge,
                 const PUT_EDGE &put_edge, const PUT_ROOT &put_root)
        : n(tree.node_number()),
          hld(tree),
          full_tree_dp(n, e),
          child_dp(n, e),
          parent_dp(n, e) {
        auto dfs_sub = [&](auto &&self, int v, int par = -1) -> void {
            for (const auto &edge : tree[v]) {
                if (edge.to == par) continue;
                self(self, edge.to, v);
                child_dp[v] =
                    merge(child_dp[v], put_edge(edge, child_dp[edge.to]));
            }
            child_dp[v] = put_root(v, child_dp[v]);
        };
        dfs_sub(dfs_sub, 0);
        auto dfs_all = [&](auto &&self, int v, int par = -1) -> void {
            std::vector<int> ch;
            std::vector<V> dp;
            V ret = e;
            for (const auto &edge : tree[v]) {
                if (edge.to == par) {
                    ret = put_edge(edge, parent_dp[v]);
                } else {
                    ch.emplace_back(edge.to);
                    dp.emplace_back(put_edge(edge, child_dp[edge.to]));
                }
            }
            int sz = (int)ch.size();
            if (ch.empty()) {
                full_tree_dp[v] = put_root(v, ret);
                return;
            }
            std::vector<V> lcum(sz, ret);
            for (int i = 0; i < sz - 1; i++) {
                lcum[i + 1] = merge(lcum[i], dp[i]);
            }
            V rcum = e;
            for (int i = sz - 1; i >= 0; i--) {
                parent_dp[ch[i]] = put_root(v, merge(lcum[i], rcum));
                rcum = merge(rcum, dp[i]);
            }
            for (int i = 0; i < sz; i++) {
                self(self, ch[i], v);
            }
            full_tree_dp[v] = put_root(v, merge(rcum, ret));
        };
        dfs_all(dfs_all, 0);
    }

    V get(int v) const {
        return get(v, v);
    }

    V get(int v, int root) const {
        if (root == v) return full_tree_dp[v];
        if (!hld.is_subtree(v, root)) {
            return child_dp[v];
        }
        return parent_dp[hld.jump(v, root, 1)];
    }

    std::vector<V> get_full_dp() const {
        return full_tree_dp;
    }

  private:
    int n;
    heavy_light_decomposition<T> hld;
    std::vector<V> full_tree_dp;
    std::vector<V> child_dp;
    std::vector<V> parent_dp;
};

}  // namespace ebi
#line 2 "utility/random_number_generator.hpp"

#line 5 "utility/random_number_generator.hpp"
#include <numeric>

#include <random>

#line 8 "utility/random_number_generator.hpp"

namespace ebi {

struct random_number_generator {
    random_number_generator(int seed = -1) {
        if (seed < 0) seed = rnd();
        mt.seed(seed);
    }

    void set_seed(int seed) {
        mt.seed(seed);
    }

    template <class T> T get(T a, T b) {
        std::uniform_int_distribution<T> dist(a, b - 1);
        return dist(mt);
    }

    std::vector<int> get_permutation(int n) {
        std::vector<int> p(n);
        std::iota(p.begin(), p.end(), 0);
        std::shuffle(p.begin(), p.end(), mt);
        return p;
    }

  private:
    std::mt19937_64 mt;
    std::random_device rnd;
};

}  // namespace ebi
#line 9 "tree/subtree_hash.hpp"

namespace ebi {

template <class T> struct subtree_hash {
  private:
    using V = std::pair<int, modint61>;

    static modint61 hash_base(int k) {
        static std::vector<modint61> r;
        static random_number_generator rng;
        while ((int)r.size() <= k) {
            r.emplace_back(rng.get<std::uint64_t>(0, modint61::mod()));
        }
        return r[k];
    }

    static auto merge() {
        return [&](V a, V b) -> V {
            return {std::max(a.first, b.first), a.second * b.second};
        };
    }

    static auto put_edge() {
        return [&](Graph<T>::edge_type, V a) -> V {
            return {a.first + 1, a.second};
        };
    }

    static auto put_root() {
        return [&](int, V a) -> V {
            return {a.first, a.second + hash_base(a.first)};
        };
    }

  public:
    subtree_hash(const Graph<T> &tree)
        : dp(tree, V{0, 1}, merge(), put_edge(), put_root()) {}

    modint61 get(int v) const {
        return dp.get(v).second;
    }

    modint61 get(int v, int root) {
        return dp.get(v, root).second;
    }

  private:
    rerooting_dp<T, V> dp;
};

}  // namespace ebi
Back to top page