shogo-library

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

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/unittest/graph/chinese-postman.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// chinese-postman.hpp の chinese_postman を、辺を何回通るかをすべて試す愚直な実装と比べる
// chinese_postman_restore は、返した閉路がつながっていて、すべての辺を 1 回以上通り、長さが最小値と一致するかを確かめる
// 各辺を 1 回か 2 回通るとしてよい (3 回以上通るなら 2 回減らしても条件を満たす) ので、
// 2 回通る辺の集合を全探索し、すべての頂点の次数が偶数になるものの最小を求める
// 自己ループ・多重辺・辺を持たない頂点・連結でないグラフも調べる
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#include "../../../src/graph/chinese-postman.hpp"

#include <iostream>
#include <random>
#include <vector>

#include "../../../src/data_structures/unionfind.hpp"

int main() {
    std::mt19937_64 rng(314);
    bool ok = true;
    {
        Graph<long long> g(3);
        if (chinese_postman(g) != 0LL) ok = false;
        auto r = chinese_postman_restore(g);
        if (!r || r->cost != 0 || r->vertices != std::vector<long long>{0} || !r->edges.empty()) ok = false;
    }
    for (int rep = 0; rep < 3000 && ok; rep++) {
        int n = rng() % 7 + 1, m = rng() % 11;
        Graph<long long> g(n);
        std::vector<int> us(m), vs(m);
        std::vector<long long> ws(m);
        UnionFind uf(n);
        for (int i = 0; i < m; i++) {
            us[i] = rng() % n, vs[i] = rng() % n, ws[i] = rng() % 10;
            g.add_edge(us[i], vs[i], ws[i]);
            uf.merge(us[i], vs[i]);
        }
        bool connected = true;
        int some = m > 0 ? us[0] : -1;
        for (int i = 0; i < m; i++) connected &= uf.same(us[i], some);
        long long best = -1;
        if (connected) {
            for (int S = 0; S < (1 << m); S++) {
                std::vector<int> deg(n, 0);
                long long cost = 0;
                for (int i = 0; i < m; i++) {
                    int times = (S >> i & 1) ? 2 : 1;
                    deg[us[i]] += times, deg[vs[i]] += times;
                    cost += times * ws[i];
                }
                bool even = true;
                for (int v = 0; v < n; v++) even &= deg[v] % 2 == 0;
                if (even && (best == -1 || cost < best)) best = cost;
            }
        }
        auto res = chinese_postman(g);
        auto path = chinese_postman_restore(g);
        if (!connected) {
            if (res || path) ok = false;
            continue;
        }
        if (!res || *res != best || !path) {
            ok = false;
            continue;
        }
        // 閉路: 頂点の列と辺の列がつながっていて始点に戻り、元の辺をすべて 1 回以上通り、長さが最小値
        const auto& [cost, vertices, edges] = *path;
        if (cost != best || vertices.size() != edges.size() + 1 || vertices.front() != vertices.back()) ok = false;
        std::vector<int> times(m, 0);
        long long len = 0;
        for (int k = 0; k < static_cast<int>(edges.size()) && ok; k++) {
            const auto& e = edges[k];
            if (e.src != vertices[k] || e.dst != vertices[k + 1] || e.id < 0 || e.id >= m) {
                ok = false;
                break;
            }
            bool same = e.src == us[e.id] && e.dst == vs[e.id];
            bool rev = e.src == vs[e.id] && e.dst == us[e.id];
            if (!(same || rev) || e.cost != ws[e.id]) ok = false;
            times[e.id]++;
            len += e.cost;
        }
        for (int i = 0; i < m; i++)
            if (times[i] == 0) ok = false;
        if (len != best) ok = false;
    }
    if (ok) std::cout << "Hello World" << std::endl;
}
#line 1 "test/unittest/graph/chinese-postman.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// chinese-postman.hpp の chinese_postman を、辺を何回通るかをすべて試す愚直な実装と比べる
// chinese_postman_restore は、返した閉路がつながっていて、すべての辺を 1 回以上通り、長さが最小値と一致するかを確かめる
// 各辺を 1 回か 2 回通るとしてよい (3 回以上通るなら 2 回減らしても条件を満たす) ので、
// 2 回通る辺の集合を全探索し、すべての頂点の次数が偶数になるものの最小を求める
// 自己ループ・多重辺・辺を持たない頂点・連結でないグラフも調べる
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#line 2 "src/graph/chinese-postman.hpp"

/**
 * @file chinese-postman.hpp
 * @brief 中国人郵便配達問題
 */

#include <algorithm>
#include <cassert>
#include <limits>
#include <optional>
#include <utility>
#include <vector>

#line 2 "src/graph/eulerian-trail.hpp"

/**
 * @file eulerian-trail.hpp
 * @brief オイラー路
 */

#line 9 "src/graph/eulerian-trail.hpp"
#include <cstdlib>
#line 13 "src/graph/eulerian-trail.hpp"

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

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

#line 9 "src/graph/graph.hpp"
#include <iostream>
#line 12 "src/graph/graph.hpp"

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

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

   public:
    /**
     * @brief デフォルトコンストラクタ
     */
    Graph() : n(0), m(0), g(0) {}
    /**
     * @brief コンストラクタ
     * @param n 頂点数
     */
    explicit Graph(long long n) : n(n), m(0), g(n) {}
    /**
     * @brief 頂点数
     */
    long long size() const { return n; }
    /**
     * @brief 辺数 (無向辺は 1 本と数える)
     */
    long long edge_count() const { return m; }
    /**
     * @brief 無向辺を追加する
     * @param u 始点
     * @param v 終点
     * @param w コスト 省略したら1
     */
    void add_edge(long long u, long long v, Cost w = 1) {
        assert(0 <= u && u < n && 0 <= v && v < n);
        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(long long u, long long v, Cost w = 1) {
        assert(0 <= u && u < n && 0 <= v && v < n);
        g[u].push_back({u, v, w, m++});
    }
    /**
     * @brief 辺の情報を標準入力から受け取って追加する
     * @param m 辺の数
     * @param padding 頂点番号を入力からいくつずらすか 省略したら-1
     * @param weighted 辺の重みが入力されるか 省略したらfalseとなり、重み1で辺が追加される
     * @param directed 有向グラフかどうか 省略したらfalse
     */
    void read(long long m, long long padding = -1, bool weighted = false, bool directed = false) {
        for (long long i = 0; i < m; i++) {
            long long 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 const std::vector<Edge>& vから出る辺のリスト
     */
    const std::vector<Edge>& operator[](long long v) const {
        assert(0 <= v && v < n);
        return g[v];
    }
    /**
     * @brief 辺のリスト
     * @return std::vector<Edge> 辺のリスト(idの昇順)
     *
     * 無向辺は代表して1つだけ格納される。その src と dst の向きは規定しない
     * 有向辺は追加したときの向きのまま格納される
     */
    std::vector<Edge> edges() const {
        std::vector<Edge> res(m);
        for (long long i = 0; i < n; i++) {
            for (auto& e : g[i]) {
                res[e.id] = e;
            }
        }
        return res;
    }
};

/**
 * @brief 経路 (路・閉路)。長さ cost、たどる頂点の列 vertices、たどる辺の列 edges
 *
 * edges[k] は vertices[k] から vertices[k + 1] へ向かう (edges[k].src == vertices[k]、edges[k].dst == vertices[k + 1])
 * vertices は edges より 1 つ多い。辺がなくても始点 1 つが入る。閉路なら vertices.front() == vertices.back()
 * auto [cost, vertices, edges] = *shortest_path(g, s, t); のように受け取れる
 */
template <typename Cost>
struct Path {
    Cost cost;                                      //!< 長さ (辺のコストの和)
    std::vector<long long> vertices;                //!< たどる頂点 (始点から順に)
    std::vector<typename Graph<Cost>::Edge> edges;  //!< たどる辺 (始点側から順に)
};

namespace internal_graph {
/**
 * @brief 始点 s と、s からたどる順に並べた辺 edges から Path を作る。cost は辺のコストの和
 */
template <typename Cost>
Path<Cost> make_path(long long s, std::vector<typename Graph<Cost>::Edge> edges) {
    Path<Cost> res{Cost{}, {s}, std::move(edges)};
    for (const auto& e : res.edges) {
        assert(e.src == res.vertices.back());
        res.cost += e.cost;
        res.vertices.push_back(e.dst);
    }
    return res;
}
}  // namespace internal_graph
#line 15 "src/graph/eulerian-trail.hpp"

namespace internal_eulerian_trail {

/**
 * @brief s から Hierholzer 法でたどり、使った辺をたどる順に並べる
 *
 * 辺を番号で使用済みにするので、無向辺 (同じ番号の辺が 2 本ある) も 1 回しか通らない
 * すべての辺を使えなければ (連結でなければ) std::nullopt を返す
 */
template <typename Cost>
std::optional<std::vector<typename Graph<Cost>::Edge>> hierholzer(const Graph<Cost>& graph, long long s) {
    using Edge = typename Graph<Cost>::Edge;
    std::vector<int> iter(graph.size(), 0);
    std::vector<bool> used(graph.edge_count(), false);
    std::vector<Edge> res;
    // (今いる頂点, そこへ来るのに使った辺)。始点では辺の src == -1
    std::vector<std::pair<long long, Edge>> st = {{s, Edge()}};
    while (!st.empty()) {
        long long v = st.back().first;
        int& it = iter[v];
        while (it < static_cast<int>(graph[v].size()) && used[graph[v][it].id]) it++;
        if (it == static_cast<int>(graph[v].size())) {
            if (st.back().second.src != -1) res.push_back(st.back().second);
            st.pop_back();
        } else {
            const Edge& e = graph[v][it++];
            used[e.id] = true;
            st.push_back({e.dst, e});
        }
    }
    if (static_cast<long long>(res.size()) != graph.edge_count()) return std::nullopt;
    std::reverse(res.begin(), res.end());
    return res;
}

// 辺がないグラフのオイラー路。頂点 0 だけの路 (頂点もなければ空)
template <typename Cost>
Path<Cost> empty_trail(const Graph<Cost>& graph) {
    if (graph.size() == 0) return {Cost{}, {}, {}};
    return {Cost{}, {0}, {}};
}

}  // namespace internal_eulerian_trail

/**
 * @brief 有向グラフのオイラー路 (すべての辺をちょうど 1 回ずつ通る路) を 1 つ求める
 *
 * Hierholzer 法 O(n + m)
 * @return std::optional<Path<Cost>> 路 (長さはすべての辺のコストの和、たどる頂点、たどる辺)。オイラー路がなければ std::nullopt
 * 辺がないときは、頂点 0 だけの路を返す (頂点もなければ頂点の列も空)。始点と終点が同じになるのは、閉路として回れるときだけ
 */
template <typename Cost = long long>
std::optional<Path<Cost>> eulerian_trail_directed(const Graph<Cost>& graph) {
    if (graph.edge_count() == 0) return internal_eulerian_trail::empty_trail(graph);
    std::vector<long long> diff(graph.size(), 0);  // 出次数 - 入次数
    for (long long v = 0; v < graph.size(); v++) {
        for (long long u : graph[v]) diff[v]++, diff[u]--;
    }
    // 出次数が 1 多い頂点があればそこから始める。なければ辺を持つ頂点から
    long long s = -1, plus = 0;
    for (long long v = 0; v < graph.size(); v++) {
        if (std::abs(diff[v]) > 1) return std::nullopt;
        if (diff[v] == 1) s = v, plus++;
    }
    if (plus > 1) return std::nullopt;
    for (long long v = 0; s == -1; v++) {
        if (!graph[v].empty()) s = v;
    }
    auto trail = internal_eulerian_trail::hierholzer(graph, s);
    if (!trail) return std::nullopt;
    return internal_graph::make_path<Cost>(s, std::move(*trail));
}

/**
 * @brief 無向グラフのオイラー路 (すべての辺をちょうど 1 回ずつ通る路) を 1 つ求める
 *
 * Hierholzer 法 O(n + m)
 * @return std::optional<Path<Cost>> 路 (長さはすべての辺のコストの和、たどる頂点、辺はたどる向きにしたもの)。オイラー路がなければ std::nullopt
 * 辺がないときは、頂点 0 だけの路を返す (頂点もなければ頂点の列も空)。自己ループ・多重辺があってもよい
 */
template <typename Cost = long long>
std::optional<Path<Cost>> eulerian_trail_undirected(const Graph<Cost>& graph) {
    if (graph.edge_count() == 0) return internal_eulerian_trail::empty_trail(graph);
    // 次数が奇数の頂点が 2 個ならその一方から、0 個なら辺を持つ頂点から始める
    long long s = -1, odd = 0;
    for (long long v = 0; v < graph.size(); v++) {
        if (graph[v].size() % 2 == 1) s = v, odd++;
    }
    if (odd > 2) return std::nullopt;
    for (long long v = 0; s == -1; v++) {
        if (!graph[v].empty()) s = v;
    }
    auto trail = internal_eulerian_trail::hierholzer(graph, s);
    if (!trail) return std::nullopt;
    return internal_graph::make_path<Cost>(s, std::move(*trail));
}
#line 2 "src/graph/shortest-path.hpp"

/**
 * @file shortest-path.hpp
 * @brief 最短路
 */

#line 10 "src/graph/shortest-path.hpp"
#include <deque>
#include <functional>
#line 14 "src/graph/shortest-path.hpp"
#include <queue>
#line 17 "src/graph/shortest-path.hpp"

#line 19 "src/graph/shortest-path.hpp"

/**
 * @brief 1 点から全点への最短路の結果
 *
 * auto [dist, prev] = shortest_path_dijkstra(g, s); のように受け取れる
 */
template <typename Cost>
struct ShortestPath {
    using Edge = typename Graph<Cost>::Edge;
    std::vector<Cost> dist;  //!< 各頂点への最短路長
    std::vector<Edge> prev;  //!< 各頂点への最短路上の直前の辺 (始点と未到達の頂点では src == -1)
    /**
     * @brief 始点から t への最短路 (長さ、たどる頂点、たどる辺)
     * cost は dist[t] (shortest_path_bfs では辺の本数)
     * @return std::optional<Path<Cost>> t が始点なら長さ 0、頂点は t だけ、辺は空。未到達なら std::nullopt
     * @note 負閉路の影響を受ける頂点では最短路が定まらない (assert で落ちる)
     */
    std::optional<Path<Cost>> path(long long t) const {
        // 直前の辺がないのは始点と未到達の頂点。始点の距離は 0 で、未到達の距離 inf は正なので区別できる
        if (prev[t].src == -1 && dist[t] != Cost{}) return std::nullopt;
        Path<Cost> res{dist[t], {t}, {}};
        while (prev[t].src != -1) {
            res.edges.push_back(prev[t]);
            assert(res.edges.size() < prev.size() && "path: negative cycle");
            t = prev[t].src;
            res.vertices.push_back(t);
        }
        std::reverse(res.vertices.begin(), res.vertices.end());
        std::reverse(res.edges.begin(), res.edges.end());
        return res;
    }
};

namespace internal_shortest_path {

template <typename Cost>
ShortestPath<Cost> bfs(const Graph<Cost>& graph, long long s, Cost inf) {
    std::vector<Cost> dist(graph.size(), inf);
    std::vector<typename Graph<Cost>::Edge> prev(graph.size());
    std::queue<long long> que;
    dist[s] = 0;
    que.push(s);
    while (!que.empty()) {
        long long u = que.front();
        que.pop();
        for (auto& e : graph[u]) {
            if (dist[e.dst] == inf) {
                dist[e.dst] = dist[e.src] + 1;
                prev[e.dst] = e;
                que.push(e.dst);
            }
        }
    }
    return {dist, prev};
}

// target が -1 でなければ、target の距離が決まった時点で打ち切る
template <typename Cost>
ShortestPath<Cost> dijkstra(const Graph<Cost>& graph, long long s, Cost inf, long long target = -1) {
    for (long long v = 0; v < graph.size(); v++) {
        for (const auto& e : graph[v]) assert(!(e.cost < Cost{}) && "negative edge (use shortest_path_bellman_ford)");
    }
    std::vector<Cost> dist(graph.size(), inf);
    std::vector<typename Graph<Cost>::Edge> prev(graph.size());
    using Node = std::pair<Cost, long long>;
    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;
        if (u == target) break;
        for (auto& e : graph[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};
}

}  // namespace internal_shortest_path

/**
 * @brief s から t への最短路 (Dijkstra。t の距離が決まった時点で打ち切る) O(m log m)
 *
 * @return std::optional<Path<Cost>> 長さ、たどる頂点、たどる辺。届かなければ std::nullopt。s == t なら長さ 0、頂点は s だけ、辺は空
 * @note 負の辺があると assert で落ちる (負の辺があるなら shortest_path_bellman_ford)
 */
template <typename Cost = long long>
std::optional<Path<Cost>> shortest_path(const Graph<Cost>& graph, long long s, long long t) {
    assert(0 <= s && s < graph.size());
    assert(0 <= t && t < graph.size());
    return internal_shortest_path::dijkstra(graph, s, std::numeric_limits<Cost>::max() / 4, t).path(t);
}

/**
 * @brief ある頂点から各頂点への最短路 (Dijkstra) O(m log m)
 *
 * @param s 始点
 * @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
 * @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
 * @note 負の辺があると assert で落ちる (負の辺があるなら shortest_path_bellman_ford)
 */
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_dijkstra(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    assert(0 <= s && s < graph.size());
    return internal_shortest_path::dijkstra(graph, s, inf);
}

/**
 * @brief 辺の重みをすべて 1 とみなして、ある頂点から各頂点への最短路 (BFS) O(n + m)
 *
 * @param s 始点
 * @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
 * @return ShortestPath 各頂点への最短路長 (辺の本数、dist) と、各頂点への最短路上の直前の辺 (prev)
 */
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_bfs(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    assert(0 <= s && s < graph.size());
    return internal_shortest_path::bfs(graph, s, inf);
}

/**
 * @brief ある頂点から各頂点への最短路
 *
 * @param s 始点
 * @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると std::numeric_limits<Cost>::max() / 4 負閉路の影響を受ける点は -inf
 * @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
 */
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_bellman_ford(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    assert(0 <= s && s < graph.size());
    const long long n = graph.size();
    std::vector<Cost> dist(n, inf);
    std::vector<typename Graph<Cost>::Edge> prev(n);
    dist[s] = Cost{};

    for (long long i = 1; i < n; i++) {
        bool changed = false;
        for (long long j = 0; j < n; j++)
            for (const auto& e : graph[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 (long long i = 0; i < n; i++) {
        bool changed = false;
        for (long long j = 0; j < n; j++)
            for (const auto& e : graph[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};
}

/**
 * @brief 辺のコストが 0 か 1 だけのグラフで、ある頂点から各頂点への最短路 (01-BFS) O(n + m)
 *
 * @param s 始点
 * @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
 * @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
 */
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_01bfs(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    assert(0 <= s && s < graph.size());
    std::vector<Cost> dist(graph.size(), inf);
    std::vector<typename Graph<Cost>::Edge> prev(graph.size());
    std::deque<long long> que;
    dist[s] = 0;
    que.push_back(s);
    while (!que.empty()) {
        long long u = que.front();
        que.pop_front();
        for (auto& e : graph[u]) {
            assert(e.cost == 0 || e.cost == 1);
            if (dist[e.dst] == inf || dist[e.dst] > dist[u] + e.cost) {
                dist[e.dst] = dist[u] + e.cost;
                prev[e.dst] = e;
                if (e.cost == 0)
                    que.push_front(e.dst);
                else
                    que.push_back(e.dst);
            }
        }
    }
    return {dist, prev};
}

/**
 * @brief 全点対間の最短路長 (Floyd-Warshall) O(n^3)
 *
 * @param inf 未到達を表す値 省略すると std::numeric_limits<Cost>::max() / 4
 * @return std::vector<std::vector<Cost>> dist[i][j] が i から j への最短路長 (到達できなければ inf)
 * @note 負の辺があってもよい。dist[i][i] < 0 となる i があれば負閉路がある
 * 負閉路があるときの値は -inf 以上に切り詰めるので、あふれない (負閉路の影響を受ける組の値は最短路長ではない)
 */
template <typename Cost = long long>
std::vector<std::vector<Cost>> shortest_path_floyd_warshall(const Graph<Cost>& graph, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    const long long n = graph.size();
    std::vector<std::vector<Cost>> dist(n, std::vector<Cost>(n, inf));
    for (long long i = 0; i < n; i++) dist[i][i] = Cost{};
    for (long long i = 0; i < n; i++) {
        for (auto& e : graph[i]) dist[i][e.dst] = std::min(dist[i][e.dst], e.cost);
    }
    for (long long k = 0; k < n; k++) {
        for (long long i = 0; i < n; i++) {
            if (dist[i][k] == inf) continue;
            for (long long j = 0; j < n; j++) {
                if (dist[k][j] == inf) continue;
                // dist は -inf 以上 inf 以下なので、和は -2 inf 以上であふれない
                Cost d = dist[i][k] + dist[k][j];
                if (d < -inf) d = -inf;
                if (d < dist[i][j]) dist[i][j] = d;
            }
        }
    }
    return dist;
}
#line 18 "src/graph/chinese-postman.hpp"

namespace internal_chinese_postman {
/**
 * @brief 中国人郵便配達問題の DP
 * odd: 次数が奇数の頂点、sp[i]: odd[i] からの最短路、pair_with[S]: 集合 S の最小の頂点の相手 (odd の添字)
 * cost: 最小の長さ。辺がすべて 1 つの連結成分に入っていなければ std::nullopt
 */
template <typename Cost>
struct Solver {
    std::optional<Cost> cost;
    long long start = -1;  // 辺を持つ頂点の 1 つ (辺がなければ -1)
    std::vector<long long> odd;
    std::vector<ShortestPath<Cost>> sp;
    std::vector<int> pair_with;
};
template <typename Cost>
Solver<Cost> solve(const Graph<Cost>& graph, Cost inf) {
    const long long n = graph.size();
    Solver<Cost> res;
    Cost total{};
    for (const auto& e : graph.edges()) {
        assert(e.cost >= Cost{});
        total += e.cost;
    }
    for (long long v = 0; v < n; v++) {
        if (!graph[v].empty()) res.start = v;
        // 自己ループは隣接リストに 2 回入るので、次数に 2 と数えられる
        if (graph[v].size() % 2 == 1) res.odd.push_back(v);
    }
    if (res.start == -1) {
        res.cost = Cost{};
        return res;
    }
    // 辺を持つ頂点がすべて連結か
    std::vector<Cost> d = shortest_path_dijkstra(graph, res.start, inf).dist;
    for (long long v = 0; v < n; v++) {
        if (!graph[v].empty() && d[v] == inf) return res;
    }
    const auto& odd = res.odd;
    const int k = static_cast<int>(odd.size());
    assert(k < 31);
    for (int i = 0; i < k; i++) res.sp.push_back(shortest_path_dijkstra(graph, odd[i], inf));
    // dp[S]: 奇数次数の頂点の集合 S を組にする最小コスト。S の最小の頂点の相手を決める
    std::vector<Cost> dp(1 << k, inf);
    res.pair_with.assign(1 << k, -1);
    dp[0] = Cost{};
    for (int S = 1; S < (1 << k); S++) {
        if (__builtin_popcount(S) % 2 == 1) continue;
        int i = __builtin_ctz(S);
        for (int j = i + 1; j < k; j++) {
            if (!(S >> j & 1)) continue;
            int T = S ^ (1 << i) ^ (1 << j);
            if (dp[T] != inf && dp[T] + res.sp[i].dist[odd[j]] < dp[S]) {
                dp[S] = dp[T] + res.sp[i].dist[odd[j]];
                res.pair_with[S] = j;
            }
        }
    }
    res.cost = total + dp[(1 << k) - 1];
    return res;
}
}  // namespace internal_chinese_postman

/**
 * @brief 無向グラフで、すべての辺を 1 回以上通って始点に戻る閉路の長さの最小値 (中国人郵便配達問題)
 *
 * 次数が奇数の頂点 (k 個) を 2 個ずつ組にして、組の間の最短路を余分に通ればよい。
 * 奇数次数の頂点ごとに Dijkstra 法で距離を求め、組にする最小コストを bit DP で求める。O(k m log m + 2^k k)
 * 始点はどこでもよい (辺を持つ頂点のどれから始めても同じ長さになる)
 * @param inf 到達できないことを表す値 省略すると std::numeric_limits<Cost>::max() / 4
 * @return std::optional<Cost> 辺がすべて 1 つの連結成分に入っていなければ std::nullopt。辺がなければ 0
 * @note 辺のコストは 0 以上であること。k は 20 程度まで。自己ループ・多重辺があってもよい
 */
template <typename Cost = long long>
std::optional<Cost> chinese_postman(const Graph<Cost>& graph, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    return internal_chinese_postman::solve(graph, inf).cost;
}

/**
 * @brief 中国人郵便配達問題の最短の閉路を 1 つ求める
 *
 * 組にした奇数次数の頂点の間の最短路の辺を複製し、すべての次数を偶数にしたグラフでオイラー閉路をたどる。計算量は chinese_postman と同じ
 * @param inf chinese_postman と同じ
 * @return std::optional<Path<Cost>> 閉路 (長さ、たどる頂点、たどる辺)。辺は元のグラフの辺 (番号も元のもの) をたどる向きにしたもので、
 * 複製した辺は同じ辺が何度か現れる。辺がすべて 1 つの連結成分に入っていなければ std::nullopt。辺がなければ頂点 0 だけ (頂点もなければ空) の閉路
 * @note chinese_postman と同じ
 */
template <typename Cost = long long>
std::optional<Path<Cost>> chinese_postman_restore(const Graph<Cost>& graph, Cost inf = std::numeric_limits<Cost>::max() / 4) {
    using Edge = typename Graph<Cost>::Edge;
    auto res = internal_chinese_postman::solve(graph, inf);
    if (!res.cost) return std::nullopt;
    if (res.start == -1) return Path<Cost>{Cost{}, graph.size() == 0 ? std::vector<long long>{} : std::vector<long long>{0}, {}};
    // 元の辺と、組の間の最短路の辺を複製したものを並べた多重グラフ。orig[新しい番号] は元の辺の番号
    Graph<Cost> h(graph.size());
    std::vector<long long> orig;
    auto add = [&](const Edge& e) {
        h.add_edge(e.src, e.dst, e.cost);
        orig.push_back(e.id);
    };
    for (const auto& e : graph.edges()) add(e);
    const int k = static_cast<int>(res.odd.size());
    for (int S = (1 << k) - 1; S > 0;) {
        int i = __builtin_ctz(S), j = res.pair_with[S];
        const auto path = res.sp[i].path(res.odd[j]);  // 一時オブジェクトのまま ->edges を回すと先に破棄される
        for (const auto& e : path->edges) add(e);
        S ^= (1 << i) | (1 << j);
    }
    // すべての頂点の次数が偶数なので、オイラー閉路が見つかる
    auto trail = *internal_eulerian_trail::hierholzer(h, res.start);
    for (auto& e : trail) e.id = orig[e.id];
    return internal_graph::make_path<Cost>(res.start, std::move(trail));
}
#line 11 "test/unittest/graph/chinese-postman.test.cpp"

#line 13 "test/unittest/graph/chinese-postman.test.cpp"
#include <random>
#line 15 "test/unittest/graph/chinese-postman.test.cpp"

#line 2 "src/data_structures/unionfind.hpp"

/**
 * @file unionfind.hpp
 * @brief UnionFind
 */

#line 12 "src/data_structures/unionfind.hpp"

namespace internal_unionfind {
/**
 * @brief 各要素の代表元から、連結成分ごとの要素のリストを作る
 * @param leader 要素 a の代表元を返す関数
 */
template <typename F>
std::vector<std::vector<long long>> groups(long long n, F leader) {
    std::vector<long long> leader_buf(n), group_size(n);
    for (long long i = 0; i < n; i++) {
        leader_buf[i] = leader(i);
        group_size[leader_buf[i]]++;
    }
    std::vector<std::vector<long long>> result(n);
    for (long long i = 0; i < n; i++) {
        result[i].reserve(group_size[i]);
    }
    for (long long i = 0; i < n; i++) {
        result[leader_buf[i]].push_back(i);
    }
    result.erase(std::remove_if(result.begin(), result.end(), [&](const std::vector<long long>& v) { return v.empty(); }), result.end());
    return result;
}
}  // namespace internal_unionfind

/**
 * @brief 無向グラフに対して「辺の追加」、「2頂点が連結かの判定」をする
 */
class UnionFind {
   protected:
    long long _n;
    // 負ならサイズ、非負なら親 (メモリを抑えるため int で持つ)
    std::vector<int> parent_or_size;

   public:
    /**
     * @brief merge の戻り値
     *
     * if (uf.merge(a, b)) で新しく統合したかを判定でき、
     * auto [r, merged] = uf.merge(a, b); で代表元も受け取れる
     */
    struct MergeResult {
        long long leader;  //!< 統合後の代表元
        bool merged;       //!< 新しく統合したか (もともと同じ連結成分なら false)
        explicit operator bool() const { return merged; }
    };

    UnionFind() : _n(0) {}
    explicit UnionFind(long long n) : _n(n), parent_or_size(n, -1) {}

    /**
     * @brief 辺(a,b)を足す
     * @return 統合後の代表元と、新しく統合したか
     */
    MergeResult merge(long long a, long long b) {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        long long x = leader(a), y = leader(b);
        if (x == y) return {x, false};
        if (-parent_or_size[x] < -parent_or_size[y]) std::swap(x, y);
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = static_cast<int>(x);
        return {x, true};
    }
    /**
     * @brief 頂点a,bが連結かどうか
     */
    bool same(long long a, long long b) {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }
    /**
     * @brief 頂点aの属する連結成分の代表元
     */
    long long leader(long long a) {
        assert(0 <= a && a < _n);
        if (parent_or_size[a] < 0) return a;
        int x = static_cast<int>(a);
        while (parent_or_size[x] >= 0) {
            x = parent_or_size[x];
        }
        while (parent_or_size[a] >= 0) {
            int t = parent_or_size[a];
            parent_or_size[a] = x;
            a = t;
        }
        return x;
    }
    /**
     * @brief 頂点aの属する連結成分のサイズ
     */
    long long size(long long a) {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }
    /**
     * @brief グラフを連結成分に分け、その情報を返す
     * @return 「一つの連結成分の頂点番号のリスト」のリスト
     */
    std::vector<std::vector<long long>> groups() {
        return internal_unionfind::groups(_n, [&](long long a) { return leader(a); });
    }
};
#line 17 "test/unittest/graph/chinese-postman.test.cpp"

int main() {
    std::mt19937_64 rng(314);
    bool ok = true;
    {
        Graph<long long> g(3);
        if (chinese_postman(g) != 0LL) ok = false;
        auto r = chinese_postman_restore(g);
        if (!r || r->cost != 0 || r->vertices != std::vector<long long>{0} || !r->edges.empty()) ok = false;
    }
    for (int rep = 0; rep < 3000 && ok; rep++) {
        int n = rng() % 7 + 1, m = rng() % 11;
        Graph<long long> g(n);
        std::vector<int> us(m), vs(m);
        std::vector<long long> ws(m);
        UnionFind uf(n);
        for (int i = 0; i < m; i++) {
            us[i] = rng() % n, vs[i] = rng() % n, ws[i] = rng() % 10;
            g.add_edge(us[i], vs[i], ws[i]);
            uf.merge(us[i], vs[i]);
        }
        bool connected = true;
        int some = m > 0 ? us[0] : -1;
        for (int i = 0; i < m; i++) connected &= uf.same(us[i], some);
        long long best = -1;
        if (connected) {
            for (int S = 0; S < (1 << m); S++) {
                std::vector<int> deg(n, 0);
                long long cost = 0;
                for (int i = 0; i < m; i++) {
                    int times = (S >> i & 1) ? 2 : 1;
                    deg[us[i]] += times, deg[vs[i]] += times;
                    cost += times * ws[i];
                }
                bool even = true;
                for (int v = 0; v < n; v++) even &= deg[v] % 2 == 0;
                if (even && (best == -1 || cost < best)) best = cost;
            }
        }
        auto res = chinese_postman(g);
        auto path = chinese_postman_restore(g);
        if (!connected) {
            if (res || path) ok = false;
            continue;
        }
        if (!res || *res != best || !path) {
            ok = false;
            continue;
        }
        // 閉路: 頂点の列と辺の列がつながっていて始点に戻り、元の辺をすべて 1 回以上通り、長さが最小値
        const auto& [cost, vertices, edges] = *path;
        if (cost != best || vertices.size() != edges.size() + 1 || vertices.front() != vertices.back()) ok = false;
        std::vector<int> times(m, 0);
        long long len = 0;
        for (int k = 0; k < static_cast<int>(edges.size()) && ok; k++) {
            const auto& e = edges[k];
            if (e.src != vertices[k] || e.dst != vertices[k + 1] || e.id < 0 || e.id >= m) {
                ok = false;
                break;
            }
            bool same = e.src == us[e.id] && e.dst == vs[e.id];
            bool rev = e.src == vs[e.id] && e.dst == us[e.id];
            if (!(same || rev) || e.cost != ws[e.id]) ok = false;
            times[e.id]++;
            len += e.cost;
        }
        for (int i = 0; i < m; i++)
            if (times[i] == 0) ok = false;
        if (len != best) ok = false;
    }
    if (ok) std::cout << "Hello World" << std::endl;
}
Back to top page