shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: 全方位木DP
(src/graph/rerooting-dp.hpp)

木 Tree<Cost> のすべての頂点について、その頂点を根としたときの木 DP の値を $O(n)$ で求めます。

rerooting_dp<E, V = E>(tree, e, merge, addedge, addnode)

頂点 $u$ の子を $v_1, v_2, \dots$ とすると、次のように計算した dp[u] (型 V) を全頂点について返します。

\[\mathrm{dp}[u] = \mathrm{addnode}(\mathrm{merge}(\mathrm{addedge}(\mathrm{dp}[v_1], \mathrm{cost}_1, \mathrm{id}_1), \mathrm{merge}(\mathrm{addedge}(\mathrm{dp}[v_2], \dots), \dots)), u)\]
引数 型 意味
e E merge の単位元 (子がないときの値)
merge(a, b) (E, E) -> E 子からの値をまとめる。可換かつ結合的であること
addedge(x, cost, id) (V, Cost, int) -> E 子の DP 値 x に、子へ向かう辺 (重み cost、番号 id) の分を加える
addnode(a, u) (E, int) -> V まとめた値 a に頂点 u の分を加えて、u の DP 値にする

例: 各頂点から最も遠い頂点までの距離 (下の farthest_node_dist と同じ)

Tree<long long> t(n);
t.read(-1, true);
auto dp = rerooting_dp(
    t, 0LL,
    [](long long a, long long b) { return std::max(a, b); },  // merge: 子の中で最大
    [](long long x, long long c, int) { return x + c; },      // addedge: 辺の重みを足す
    [](long long a, int) { return a; });                      // addnode: そのまま

よく使う DP

関数 説明
farthest_node_dist(tree) 各頂点から最も遠い頂点までの距離 (重み付き)
distance_sums(tree) 各頂点から他のすべての頂点への距離の合計 (重み付き)
connected_subgraph_count<V>(tree) 各頂点について、その頂点を含む連結な部分グラフ (頂点集合) の個数。V は mint など

いずれも計算量は $O(n)$ です。

Depends on

Verified with

Code

#pragma once

/**
 * @file rerooting-dp.hpp
 * @brief 全方位木DP
 */
#include <algorithm>
#include <cstddef>
#include <type_traits>
#include <utility>
#include <vector>
#include "tree.hpp"

/**
 * @brief 全方位木DP
 * dp[u] = addnode(merge(addedge(dp[v1], uv1.cost, uv1.id), merge(addedge(dp[v2], uv2.cost, uv2.id), ...)), u) v_iはuの子
 *
 * @tparam E 可換モノイド
 * @tparam V DPの型
 * @param tree
 * @param e 可換モノイドの単位元
 * @param merge (E,E)->E 可換
 * @param addedge (V,Cost,int)->E
 * @param addnode (E,int)->V
 * @return std::vector<V>
 */
template <typename E, typename V = E, class Merge, class AddEdge, class AddNode, typename Cost>
std::vector<V> rerooting_dp(const Tree<Cost>& tree, E e, Merge merge, AddEdge addedge, AddNode addnode) {
    static_assert(std::is_invocable_r_v<E, Merge, E, E>);
    static_assert(std::is_invocable_r_v<E, AddEdge, V, Cost, int>);
    static_assert(std::is_invocable_r_v<V, AddNode, E, int>);
    RootedTree<Cost> rooted(tree, 0);
    std::vector<V> subdp(rooted.n);
    for (int u : rooted.postorder) {
        E tmp = e;
        for (auto edge : rooted.child[u]) {
            tmp = merge(tmp, addedge(subdp[edge.dst], edge.cost, edge.id));
        }
        subdp[u] = addnode(tmp, u);
    }
    std::vector<V> dp(rooted.n);
    std::vector<E> pe(rooted.n, e);
    for (int u : rooted.preorder) {
        const auto& ch = rooted.child[u];
        std::vector<E> ri(ch.size() + 1, e);
        for (std::size_t i = ch.size(); i > 0; i--) {
            ri[i - 1] = merge(ri[i], addedge(subdp[ch[i - 1].dst], ch[i - 1].cost, ch[i - 1].id));
        }
        dp[u] = addnode(merge(pe[u], ri[0]), u);
        E le = pe[u];
        for (std::size_t i = 0; i < ch.size(); i++) {
            pe[ch[i].dst] = addedge(addnode(merge(le, ri[i + 1]), u), ch[i].cost, ch[i].id);
            le = merge(le, addedge(subdp[ch[i].dst], ch[i].cost, ch[i].id));
        }
    }
    return dp;
}

/**
 * @brief 最も遠い頂点までの距離
 */
template <typename Cost>
inline std::vector<Cost> farthest_node_dist(const Tree<Cost>& tree) {
    return rerooting_dp(
        tree,
        Cost{},
        [](Cost a, Cost b) { return std::max<Cost>(a, b); },
        [](Cost a, Cost c, int) { return a + c; },
        [](Cost a, int) { return a; });
}

/**
 * @brief 他の全ての頂点との距離の合計
 */
template <typename Cost>
inline std::vector<Cost> distance_sums(const Tree<Cost>& tree) {
    using P = typename std::pair<Cost, int>;
    auto tmp = rerooting_dp(
        tree,
        P{{}, 0},
        [](P a, P b) { return P{a.first + b.first, a.second + b.second}; },
        [](P a, Cost c, int) { return P{a.first + a.second * c, a.second}; },
        [](P a, int) { return P{a.first, a.second + 1}; });
    std::vector<Cost> res;
    res.reserve(tree.n);
    for (const P& s : tmp) res.push_back(s.first);
    return res;
}

/**
 * @brief その頂点を含む連結な部分グラフの個数
 */
template <typename V, typename Cost>
inline std::vector<V> connected_subgraph_count(const Tree<Cost>& tree) {
    return rerooting_dp(
        tree,
        V(1),
        [](V a, V b) { return a * b; },
        [](V a, Cost, int) { return a + 1; },
        [](V a, int) { return a; });
}
#line 2 "src/graph/rerooting-dp.hpp"

/**
 * @file rerooting-dp.hpp
 * @brief 全方位木DP
 */
#include <algorithm>
#include <cstddef>
#include <type_traits>
#include <utility>
#include <vector>
#line 2 "src/graph/tree.hpp"

/**
 * @file tree.hpp
 * @brief 木の汎用テンプレート
*/

#line 9 "src/graph/tree.hpp"
#include <cassert>
#include <stack>

#line 2 "src/graph/graph.hpp"

/**
 * @file graph.hpp
 * @brief グラフ
 */

#line 10 "src/graph/graph.hpp"
#include <iostream>
#include <limits>
#include <queue>
#line 14 "src/graph/graph.hpp"

/**
 * @brief グラフの汎用クラス
 *
 * @tparam Cost 辺のコストの型
 */
template <typename Cost = int>
struct Graph {
    /**
     * @brief 有向辺の構造体
     *
     * operator int()を定義しているので、int型にキャストすると勝手にdstになる
     * 例えば、
     * for (auto& e : g[v]) をすると、vから出る辺が列挙されるが、
     * for (int dst : g[v]) とすると、vから出る辺の行き先が列挙される
     */
    struct Edge {
        int src = -1;   //!< 始点
        int dst = -1;   //!< 終点
        Cost cost = {}; //!< コスト
        int id = -1;    //!< 辺の番号(追加された順、無向辺の場合はidが同じで方向が逆のものが2つ存在する)
        Edge() = default;
        Edge(int src, int dst, Cost cost = 1, int id = -1) : src(src), dst(dst), cost(cost), id(id) {}
        operator int() const { return dst; }
    };

    /**
     * @brief 最短路の結果
     *
     * auto [dist, prev] = g.shortest_path(s); のように受け取れる
     */
    struct ShortestPath {
        std::vector<Cost> dist;  //!< 各頂点への最短路長
        std::vector<Edge> prev;  //!< 各頂点への最短路上の直前の辺 (始点と未到達の頂点では src == -1)
        /**
         * @brief 始点から t への最短路を構成する辺のリスト (始点側から順に)
         * @note t が始点か未到達の頂点なら空。負閉路の影響を受ける頂点では最短路が定まらない (assert で落ちる)
         */
        std::vector<Edge> path(int t) const {
            std::vector<Edge> res;
            while (prev[t].src != -1) {
                res.push_back(prev[t]);
                assert(res.size() < prev.size() && "path: negative cycle");
                t = prev[t].src;
            }
            std::reverse(res.begin(), res.end());
            return res;
        }
    };

    int n;                            //!< 頂点数
    int m;                            //!< 辺数
    std::vector<std::vector<Edge>> g; //!< グラフの隣接リスト表現

    /**
     * @brief デフォルトコンストラクタ
     */
    Graph() : n(0), m(0), g(0) {}
    /**
     * @brief コンストラクタ
     * @param n 頂点数
     */
    explicit Graph(int n) : n(n), m(0), g(n) {}
    /**
     * @brief 無向辺を追加する
     * @param u 始点
     * @param v 終点
     * @param w コスト 省略したら1
     */
    void add_edge(int u, int v, Cost w = 1) {
        g[u].push_back({u, v, w, m});
        g[v].push_back({v, u, w, m++});
    }
    /**
     * @brief 有向辺を追加する
     * @param u 始点
     * @param v 終点
     * @param w コスト 省略したら1
     */
    void add_directed_edge(int u, int v, Cost w = 1) {
        g[u].push_back({u, v, w, m++});
    }
    /**
     * @brief 辺の情報を標準入力から受け取って追加する
     * @param m 辺の数
     * @param padding 頂点番号を入力からいくつずらすか 省略したら-1
     * @param weighted 辺の重みが入力されるか 省略したらfalseとなり、重み1で辺が追加される
     * @param directed 有向グラフかどうか 省略したらfalse
     */
    void read(int m, int padding = -1, bool weighted = false, bool directed = false) {
        for (int i = 0; i < m; i++) {
            int u, v;
            std::cin >> u >> v;
            u += padding, v += padding;
            Cost c(1);
            if (weighted)
                std::cin >> c;
            if (directed)
                add_directed_edge(u, v, c);
            else
                add_edge(u, v, c);
        }
    }
    /**
     * @brief ある頂点から出る辺を列挙する
     * @param v 頂点番号
     * @return std::vector<Edge>& vから出る辺のリスト
     */
    std::vector<Edge> &operator[](int v) {
        return g[v];
    }
    /**
     * @brief ある頂点から出る辺を列挙する
     * @param v 頂点番号
     * @return const std::vector<Edge>& vから出る辺のリスト
     */
    const std::vector<Edge> &operator[](int v) const {
        return g[v];
    }
    /**
     * @brief 辺のリスト
     * @return std::vector<Edge> 辺のリスト(idの昇順)
     *
     * 無向辺は代表して1つだけ格納される
     */
    std::vector<Edge> edges() const {
        std::vector<Edge> res(m);
        for (int i = 0; i < n; i++) {
            for (auto &e : g[i]) {
                res[e.id] = e;
            }
        }
        return res;
    }
    /**
     * @brief ある頂点から各頂点への最短路
     *
     * @param s 始点
     * @param weighted 1以外のコストの辺が存在するか 省略するとtrue
     * @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると
     * @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
     */
    ShortestPath shortest_path(int s, bool weighted = true, Cost inf = -1) const {
        if (weighted)
            return shortest_path_dijkstra(s, inf);
        return shortest_path_bfs(s, inf);
    }
    /**
     * @brief ある頂点から各頂点への最短路
     *
     * @param s 始点
     * @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると std::numeric_limits<Cost>::max() / 4 負閉路の影響を受ける点は -inf
     * @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
     */
    ShortestPath bellman_ford(int s, Cost inf = std::numeric_limits<Cost>::max() / 4) const {
        std::vector<Cost> dist(n, inf);
        std::vector<Edge> prev(n);
        dist[s] = Cost{};

        for (int i = 1; i < n; i++) {
            bool changed = false;
            for (int j = 0; j < n; j++)
                for (const auto &e : g[j]) {
                    if (dist[e.src] == inf)
                        continue;
                    if (dist[e.dst] > dist[e.src] + e.cost) {
                        dist[e.dst] = dist[e.src] + e.cost;
                        if (dist[e.dst] < -inf)
                            dist[e.dst] = -inf;
                        prev[e.dst] = e;
                        changed = true;
                    }
                }
            if (!changed)
                break;
        }
        for (int i = 0; i < n; i++) {
            bool changed = false;
            for (int j = 0; j < n; j++)
                for (const auto &e : g[j]) {
                    if (dist[e.src] == inf)
                        continue;
                    if (dist[e.dst] > dist[e.src] + e.cost) {
                        dist[e.dst] = -inf;
                        prev[e.dst] = e;
                        changed = true;
                    }
                }
            if (!changed)
                break;
        }
        return {dist, prev};
    }

  private:
    ShortestPath shortest_path_bfs(int s, Cost inf) const {
        std::vector<Cost> dist(n, inf);
        std::vector<Edge> prev(n);
        std::queue<int> que;
        dist[s] = 0;
        que.push(s);
        while (!que.empty()) {
            int u = que.front();
            que.pop();
            for (auto &e : g[u]) {
                if (dist[e.dst] == inf) {
                    dist[e.dst] = dist[e.src] + 1;
                    prev[e.dst] = e;
                    que.push(e.dst);
                }
            }
        }
        return {dist, prev};
    }
    ShortestPath shortest_path_dijkstra(int s, Cost inf) const {
        std::vector<Cost> dist(n, inf);
        std::vector<Edge> prev(n);
        using Node = std::pair<Cost, int>;
        std::priority_queue<Node, std::vector<Node>, std::greater<Node>> que;
        dist[s] = 0;
        que.push({0, s});
        while (!que.empty()) {
            auto [d, u] = que.top();
            que.pop();
            if (d > dist[u])
                continue;
            for (auto &e : g[u]) {
                if (dist[e.dst] == inf || dist[e.dst] > dist[e.src] + e.cost) {
                    dist[e.dst] = dist[e.src] + e.cost;
                    prev[e.dst] = e;
                    que.push({dist[e.dst], e.dst});
                }
            }
        }
        return {dist, prev};
    }
};
#line 13 "src/graph/tree.hpp"

template <typename>
struct RootedTree;
template <typename>
struct DoublingClimbTree;

/**
 * @brief 根なし木
 * 
 * @tparam Cost = int 辺の重み
 * 
 * Graph<Cost>を継承し、すべて無向辺で表す
*/
template <typename Cost = int>
struct Tree : private Graph<Cost> {
    // Graph<Cost>* g = new Tree<Cost>(); ができてしまうと、delete時にメモリリークが発生
    // 回避するためprivate継承にして、メンバをすべてusing宣言
    using Edge = typename Graph<Cost>::Edge;
    using Graph<Cost>::n;
    using Graph<Cost>::m;
    using Graph<Cost>::g;
    using Graph<Cost>::Graph;
    using Graph<Cost>::add_edge;
    using Graph<Cost>::add_directed_edge;
    using Graph<Cost>::operator[];
    using Graph<Cost>::edges;
    using Graph<Cost>::shortest_path;
    using ShortestPath = typename Graph<Cost>::ShortestPath;

    /**
     * @brief コンストラクタ
     * 
     * @param n ノード数
     */
    Tree(int n = 0) : Graph<Cost>(n) {}

    /**
     * @brief 辺の情報を標準入力から受け取って追加する
     * @param padding  = -1 頂点番号を入力からいくつずらすか
     * @param weighted = false 辺の重みが入力されるか
     */
    void read(int padding = -1, bool weighted = false) {
        Graph<Cost>::read(this->n - 1, padding, weighted, false);
    }
    
    /**
     * @brief 木の直径
     * 
     * @param weighted = true 重み付きか
     * @return std::vector<Edge> 直径を構成する辺のリスト
     */
    std::vector<Edge> diameter(bool weighted = true) const {
        std::vector<Cost> dist = shortest_path(0, weighted).dist;
        int u = std::max_element(dist.begin(), dist.end()) - dist.begin();
        auto sp = shortest_path(u, weighted);
        int v = std::max_element(sp.dist.begin(), sp.dist.end()) - sp.dist.begin();
        return sp.path(v);
    }

    /**
     * @brief 根付き木にする
     * 
     * @param root 根
     * @return RootedTree<Cost> 根付き木のオブジェクト
     */
    [[nodiscard]]
    RootedTree<Cost> set_root(int root) const& {
        return RootedTree<Cost>(*this, root);
    }
    /**
     * @brief 根付き木にして返す
     * 
     * @param root 根
     * @return RootedTree<Cost> 根付き木のオブジェクト
     */
    [[nodiscard]]
    RootedTree<Cost> set_root(int root) && {
        return RootedTree<Cost>(std::move(*this), root);
    }

    /**
     * @brief ダブリングLCAが使える根付き木を返す
     * 
     * @param root 根
     * @return DoublingClimbTree<Cost> ダブリング済み根付き木のオブジェクト
     */
    [[nodiscard]]
    DoublingClimbTree<Cost> build_lca(int root) const& {
        RootedTree rooted_tree(*this, root);
        return DoublingClimbTree<Cost>(std::move(rooted_tree));
    }
    /**
     * @brief ダブリングLCAが使える根付き木を返す
     * 
     * @param root 根
     * @return DoublingClimbTree<Cost> ダブリング済み根付き木のオブジェクト
     */
    [[nodiscard]]
    DoublingClimbTree<Cost> build_lca(int root) && {
        RootedTree rooted_tree(std::move(*this), root);        
        return DoublingClimbTree<Cost>(std::move(rooted_tree));
    }
};

/**
 * @brief 根付き木
 * 
 * @tparam Cost = int 辺のコスト
 */
template <typename Cost = int>
struct RootedTree : private Tree<Cost> {
    using Edge = typename Tree<Cost>::Edge;
    using Tree<Cost>::n;
    using Tree<Cost>::m;
    using Tree<Cost>::g;
    using Tree<Cost>::operator[];
    using Tree<Cost>::edges;
    using Tree<Cost>::shortest_path;
    using ShortestPath = typename Tree<Cost>::ShortestPath;

    int root; //!< 根
    std::vector<Edge> par; //!< 親へ向かう辺
    std::vector<std::vector<Edge>> child; //!< 子へ向かう辺のリスト
    std::vector<Cost> depth; //!< 深さのリスト
    std::vector<Cost> height; //!< 部分木の高さのリスト
    std::vector<int> unweighted_depth; //!< 重みなしの深さのリスト
    std::vector<int> unweighted_height; //!< 重みなしの部分木の高さのリスト
    std::vector<int> sz; //!< 部分期の頂点数のリスト
    std::vector<int> preorder; //!< 先行順巡回
    std::vector<int> postorder; //!< 後行順巡回
    std::vector<std::pair<int, int>> euler_tour; //!< オイラーツアー DFS中にとおった頂点の(頂点番号,その頂点を通った回数)のリスト

    RootedTree() = delete;
    
    /**
     * @brief 親の頂点のリストから根が0の根付き木を構築するコンストラクタ
     * 
     * @param par_ 頂点0以外の親の頂点のリスト
     * @param padding = -1 parの頂点番号をいくつずらすか
     */
    RootedTree(const std::vector<int>& par_, int padding = -1) : Tree<Cost>(par_.size() + 1), root(0) {
        for(int i = 0; i < (int)par_.size(); i++) {
            this->add_edge(i + 1, par_[i] + padding);
        }
        build();
    }
    /**
     * @brief Treeから根付き木を構築するコンストラクタ(コピー)
     *
     * @param tree Tree 頂点数1以上
     * @param root 根
     */
    RootedTree(const Tree<Cost>& tree, int root) : Tree<Cost>(tree), root(root) {
        build();
    }
    /**
     * @brief Treeから根付き木を構築するコンストラクタ(ムーブ)
     *
     * @param tree Tree
     * @param root 根
     */
    RootedTree(Tree<Cost>&& tree, int root) : Tree<Cost>(std::move(tree)), root(root) {
        build();
    }
    
    /**
     * @brief ダブリングLCAが使える根付き木を得る
     * 
     * @return DoublingClimbTree<Cost> ダブリング済み根付き木のオブジェクト
     */
    [[nodiscard]]
    DoublingClimbTree<Cost> build_lca() const& {
        return DoublingClimbTree<Cost>(*this);
    }

    /**
     * @brief ダブリングLCAが使える根付き木を得る
     * 
     * @return DoublingClimbTree<Cost> ダブリング済み根付き木のオブジェクト
     */
    [[nodiscard]]
    DoublingClimbTree<Cost> build_lca() && {
        return DoublingClimbTree<Cost>(std::move(*this));
    }

private:
    void build() {
        int n = this->n;
        assert(n > 0);
        assert(0 <= root && root < n);
        par.resize(n);
        par[root] = {root, -1, 0, -1};
        child.resize(n);
        depth.resize(n);
        unweighted_depth.resize(n);
        height.resize(n);
        unweighted_height.resize(n);
        sz.resize(n);
        std::vector<int> iter(n);
        std::stack<std::pair<int, int>> stk;
        stk.emplace(root, 0);
        while(!stk.empty()) {
            auto [u, cnt] = stk.top(); stk.pop();
            euler_tour.emplace_back(u, cnt);
            if(iter[u] == 0) preorder.push_back(u);
            while(iter[u] < (int)this->g[u].size() && this->g[u][iter[u]].dst == par[u]) iter[u]++;
            if(iter[u] == (int)this->g[u].size()) {
                postorder.push_back(u);
                sz[u] = 1;
                height[u] = 0;
                unweighted_height[u] = 0;
                for(auto& e : child[u]) {
                    sz[u] += sz[e.dst];
                    if(height[u] < height[e.dst] + e.cost) {
                        height[u] = height[e.dst] + e.cost;
                    }
                    if(unweighted_height[u] < unweighted_height[e.dst] + 1) {
                        unweighted_height[u] = unweighted_height[e.dst] + 1;
                    }
                }
            } else {
                auto& e = this->g[u][iter[u]++];
                par[e.dst] = {e.dst, u, e.cost, e.id};
                child[u].push_back(e);
                depth[e.dst] = depth[u] + e.cost;
                unweighted_depth[e.dst] = unweighted_depth[u] + 1;
                stk.emplace(u, cnt + 1);
                stk.emplace(e.dst, 0);
            }
        }
    }
};

/**
 * @brief 親頂点ダブリング済み根付き木
 * 
 * @tparam Cost = int 辺の重み(注: climbでは根の重みは考えない)
 */
template <typename Cost = int>
struct DoublingClimbTree : private RootedTree<Cost> {
    using Edge = typename RootedTree<Cost>::Edge;
    using RootedTree<Cost>::n;
    using RootedTree<Cost>::m;
    using RootedTree<Cost>::g;
    using RootedTree<Cost>::operator[];
    using RootedTree<Cost>::edges;
    using RootedTree<Cost>::shortest_path;
    using ShortestPath = typename RootedTree<Cost>::ShortestPath;
    using RootedTree<Cost>::root;
    using RootedTree<Cost>::par;
    using RootedTree<Cost>::child;
    using RootedTree<Cost>::depth;
    using RootedTree<Cost>::height;
    using RootedTree<Cost>::unweighted_depth;
    using RootedTree<Cost>::unweighted_height;
    using RootedTree<Cost>::sz;
    using RootedTree<Cost>::preorder;
    using RootedTree<Cost>::postorder;
    using RootedTree<Cost>::euler_tour;

    int h; //!< ダブリングの回数
    std::vector<std::vector<int>> doubling_par; //!< jから(1<<i)頂点登った頂点(存在しない場合は-1)

    DoublingClimbTree() = delete;
    
    /**
     * @brief RootedTreeからダブリング済み根付き木を構築するコンストラクタ(コピー)
     *
     * @param tree RootedTree
     */
    DoublingClimbTree(const RootedTree<Cost>& tree) : RootedTree<Cost>(tree) {
        build();
    }

    /**
     * @brief RootedTreeからダブリング済み根付き木を構築するコンストラクタ(ムーブ)
     *
     * @param tree RootedTree
     */
    DoublingClimbTree(RootedTree<Cost>&& tree) : RootedTree<Cost>(std::move(tree)) {
        build();
    }
    
    /**
     * @brief 親の頂点のリストから根が0のダブリング済み根付き木を構築するコンストラクタ
     * 
     * @param par_ 頂点0以外の親の頂点のリスト
     * @param padding = -1 parの頂点番号をいくつずらすか
     */
    DoublingClimbTree(const std::vector<int>& par_, int padding = -1) : RootedTree<Cost>(par_, padding) {
        build();
    }
    /**
     * @brief Treeからダブリング済み根付き木を構築するコンストラクタ(コピー)
     *
     * @param tree Tree
     * @param root 根
     */
    DoublingClimbTree(const Tree<Cost>& tree, int root) : RootedTree<Cost>(tree, root) {
        build();
    }
    /**
     * @brief Treeからダブリング済み根付き木を構築するコンストラクタ(ムーブ)
     *
     * @param tree Tree
     * @param root 根
     */
    DoublingClimbTree(Tree<Cost>&& tree, int root) : RootedTree<Cost>(std::move(tree), root) {
        build();
    }
    
    /**
     * @brief 頂点uからk回を根の方向に遡った頂点
     * 
     * @param u 元の頂点
     * @param k 登る段数
     * @return int k回登った頂点
     */
    int climb(int u, int k) const {
        assert(k >= 0);
        if(k > this->unweighted_depth[u]) return -1;
        for(int i = 0; i < h; i++) {
            if(k >> i & 1) u = doubling_par[i][u];
            if(u == -1) return -1;
        }
        return u;
    }
    
    /**
     * @brief 最小共通祖先
     * 
     * @param u 頂点1
     * @param v 頂点2
     * @return int LCAの頂点番号
     */
    int lca(int u, int v) const {
        if(this->unweighted_depth[u] > this->unweighted_depth[v]) std::swap(u, v);
        v = climb(v, this->unweighted_depth[v] - this->unweighted_depth[u]);
        if(u == v) return u;
        for(int i = h - 1; i >= 0; i--) {
            int nu = doubling_par[i][u];
            int nv = doubling_par[i][v];
            if(nu == -1) continue;
            if(nu != nv) {
                u = nu;
                v = nv;
            }
        }
        return this->par[u];
    }
    
    /**
     * @brief 頂点間距離(重み付き)
     * 
     * @param u 頂点1
     * @param v 頂点2
     * @return Cost uとv間の最短経路の辺の重みの和
     */
    Cost dist(int u, int v) const {
        return this->depth[u] + this->depth[v] - this->depth[lca(u, v)] * 2;
    }
    
private:
    void build() {
        int n = this->n;
        h = 1;
        while((1 << h) < n) h++;
        doubling_par.assign(h, std::vector<int>(n, -1));
        for(int i = 0; i < n; i++) doubling_par[0][i] = this->par[i];
        for(int i = 0; i < h - 1; i++) {
            for(int j = 0; j < n; j++) {
                if(doubling_par[i][j] != -1) {
                    doubling_par[i+1][j] = doubling_par[i][doubling_par[i][j]];
                }
            }
        }
    }
};
#line 13 "src/graph/rerooting-dp.hpp"

/**
 * @brief 全方位木DP
 * dp[u] = addnode(merge(addedge(dp[v1], uv1.cost, uv1.id), merge(addedge(dp[v2], uv2.cost, uv2.id), ...)), u) v_iはuの子
 *
 * @tparam E 可換モノイド
 * @tparam V DPの型
 * @param tree
 * @param e 可換モノイドの単位元
 * @param merge (E,E)->E 可換
 * @param addedge (V,Cost,int)->E
 * @param addnode (E,int)->V
 * @return std::vector<V>
 */
template <typename E, typename V = E, class Merge, class AddEdge, class AddNode, typename Cost>
std::vector<V> rerooting_dp(const Tree<Cost>& tree, E e, Merge merge, AddEdge addedge, AddNode addnode) {
    static_assert(std::is_invocable_r_v<E, Merge, E, E>);
    static_assert(std::is_invocable_r_v<E, AddEdge, V, Cost, int>);
    static_assert(std::is_invocable_r_v<V, AddNode, E, int>);
    RootedTree<Cost> rooted(tree, 0);
    std::vector<V> subdp(rooted.n);
    for (int u : rooted.postorder) {
        E tmp = e;
        for (auto edge : rooted.child[u]) {
            tmp = merge(tmp, addedge(subdp[edge.dst], edge.cost, edge.id));
        }
        subdp[u] = addnode(tmp, u);
    }
    std::vector<V> dp(rooted.n);
    std::vector<E> pe(rooted.n, e);
    for (int u : rooted.preorder) {
        const auto& ch = rooted.child[u];
        std::vector<E> ri(ch.size() + 1, e);
        for (std::size_t i = ch.size(); i > 0; i--) {
            ri[i - 1] = merge(ri[i], addedge(subdp[ch[i - 1].dst], ch[i - 1].cost, ch[i - 1].id));
        }
        dp[u] = addnode(merge(pe[u], ri[0]), u);
        E le = pe[u];
        for (std::size_t i = 0; i < ch.size(); i++) {
            pe[ch[i].dst] = addedge(addnode(merge(le, ri[i + 1]), u), ch[i].cost, ch[i].id);
            le = merge(le, addedge(subdp[ch[i].dst], ch[i].cost, ch[i].id));
        }
    }
    return dp;
}

/**
 * @brief 最も遠い頂点までの距離
 */
template <typename Cost>
inline std::vector<Cost> farthest_node_dist(const Tree<Cost>& tree) {
    return rerooting_dp(
        tree,
        Cost{},
        [](Cost a, Cost b) { return std::max<Cost>(a, b); },
        [](Cost a, Cost c, int) { return a + c; },
        [](Cost a, int) { return a; });
}

/**
 * @brief 他の全ての頂点との距離の合計
 */
template <typename Cost>
inline std::vector<Cost> distance_sums(const Tree<Cost>& tree) {
    using P = typename std::pair<Cost, int>;
    auto tmp = rerooting_dp(
        tree,
        P{{}, 0},
        [](P a, P b) { return P{a.first + b.first, a.second + b.second}; },
        [](P a, Cost c, int) { return P{a.first + a.second * c, a.second}; },
        [](P a, int) { return P{a.first, a.second + 1}; });
    std::vector<Cost> res;
    res.reserve(tree.n);
    for (const P& s : tmp) res.push_back(s.first);
    return res;
}

/**
 * @brief その頂点を含む連結な部分グラフの個数
 */
template <typename V, typename Cost>
inline std::vector<V> connected_subgraph_count(const Tree<Cost>& tree) {
    return rerooting_dp(
        tree,
        V(1),
        [](V a, V b) { return a * b; },
        [](V a, Cost, int) { return a + 1; },
        [](V a, int) { return a; });
}
Back to top page