sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

最大流

Graph/Max_Flow.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

mf_graph<Cap>は、非負整数容量の有向グラフの最大流を求める。型名・辺の型・引数と戻り値・呼び出し形式はACLの最大流に合わせている。型はsirkit::mf_graph。Graph/Max_Flow.cppを単独で貼り付けられる。

Capには容量と追加流量が収まる整数型を渡す。ACLのint・std::int64_tに加え、bool以外の符号なし整数型・小さい整数型も使用できる。省略時はstd::int64_t。

API

nは頂点数、mは追加した元辺の数。頂点は[0,n)、元辺番号は追加順の[0,m)で、m <= INT_MAX。

mf_graph

mf_graph();
explicit mf_graph(int n);
mf_graph(const mf_graph&);
mf_graph(mf_graph&& other) noexcept;

空またはn頂点のグラフを作ります。コピーは残余を独立に保持し、ムーブ元は空になります。

制約: 頂点数・入力構造・型の前提を満たすこと。空の構築も可能です。

計算量: 空の構築はO(1)、n頂点の構築はO(n)。コピーはO(n+m)、ムーブはO(1)。

add_edge

int add_edge(int from, int to, Cap capacity);

非負容量の元辺を追加し、intの辺番号を返します。

制約: 引数の頂点番号・添字は有効範囲内です。その他の前提は共通条件に従います。

計算量: 償却O(1)。

get_edge

edge get_edge(int id);
edge get_edge(int id) const;

指定した元辺の端点・容量・現在流量などをコピーして返します。

制約: idは登録済みの有効な辺番号です。

計算量: O(1)。

edges

std::vector<edge> edges();
std::vector<edge> edges() const;

登録した元辺を追加順で返します。

制約: なし。

計算量: O(m)。

change_edge

void change_edge(int id, Cap capacity, Cap sent);

元辺の容量と流量を変更します。

制約: 端点・容量・上限と数値範囲は下記の前提に従い、既存流の流量保存を利用側で保ちます。

計算量: O(1)。

flow

Cap flow(int source, int sink);
Cap flow(int source, int sink, Cap limit);

上限以下の流量を追加し、今回の追加量を返します。上限省略時は容量型の最大値です。反復Dinic法から必要に応じてpush-relabel法へ切り替えます。

制約: 端点・容量・上限と数値範囲は下記の前提に従い、既存流の流量保存を利用側で保ちます。

計算量: O(n+n²m)時間・O(n)作業領域。上限1ではO(n+m)。

min_cut

std::vector<bool> min_cut(int source);
std::vector<bool> min_cut(int source) const;

各頂点に残余グラフでsから到達できるかをvector<bool>で返します。

制約: 端点・容量・上限と数値範囲は下記の前提に従い、既存流の流量保存を利用側で保ちます。

計算量: O(n+m)。

size

int size() const noexcept;

頂点数を返します。

制約: なし。

計算量: O(1)。

edge_count

std::size_t edge_count() const noexcept;

登録した元辺の数を返します。

制約: なし。

計算量: O(1)。

reserve_edges

void reserve_edges(std::size_t count);

指定件数を保持できる辺の記録容量を予約します。

制約: 指定件数は内部の容量上限以内です。

計算量: O(m)以下の確保・移動。

reset

void reset(int n = 0);

旧状態を破棄し、指定頂点数の空グラフへ戻します。

制約: 頂点数・入力構造・型の前提を満たすこと。空の構築も可能です。

計算量: O(n+旧領域の破棄)。

swap

void swap(mf_graph& other) noexcept;

保持するグラフ・結果・状態を交換します。

制約: なし。

計算量: O(1)。

get_edge・edges・min_cutはACLと同じ非const呼び出しに加え、constオブジェクトからも同名で呼べる。size・edge_count・reserve_edges・reset・swapは追加機能。

使用例

mf_graph<std::int64_t> graph(4);
const int id = graph.add_edge(0, 1, 5);
graph.add_edge(1, 3, 5);
const auto first = graph.flow(0, 3, 2); // 2だけ流す
const auto rest = graph.flow(0, 3);     // 残り3を流す
const auto used = graph.get_edge(id);  // used.cap == 5, used.flow == 5
const auto cut = graph.min_cut(0);     // cut[0] == true, cut[3] == false

完全な使用例 · Verify提出用コード

前提と所有

  • 自己辺・多重辺・逆向きの元辺も追加できる。change_edgeは0 <= new_flow <= new_capが前提で、他の頂点の流量保存は利用側で保証する。
  • flowの戻り値は累積ではなく今回の追加量。同じ始点・終点で継続でき、指定上限は非負とする。既定の上限はCapの最大値で、総流量が型に収まらない場合は複数回に分け、累積値を十分に広い型で保持する。
  • ACLではs != tが前提。この実装は追加仕様としてs == tを0とし、flow_limit == 0も0を返す。異なる端点で継続する場合も、利用側で現在の流量保存を保証する。
  • min_cutが最小カットを表すのは、流量を追加し終えて残余グラフでtに到達できなくなった後。上限に達して途中で止まった場合は最小とは限らない。
  • グラフと作業領域はO(n+m)。コピー構築・代入はO(n+m)で残余を独立所有する。移動構築はO(1)で、移動元は空になる。代入は自身への参照を返し、旧領域の破棄費用が加わる。コピー代入・resetの失敗時は元を保持する。
  • 入力検査は操作時に行い、SKIP_RUNTIME_CHECKSで除く。内部の辺数・添字上限と安全な容量差の計算は維持する。辺追加・flowの作業領域確保の失敗時は残余を保つ。

独立参照試験 · ACL互換・境界試験 · Library Checker Matching(単位容量)・旧AtCoder practice2 D(参考)

構築・状態と補助型

operator=

mf_graph& operator=(mf_graph other) noexcept;

コピー/ムーブ代入し、自身への参照を返します。

制約: なし。

計算量: コピーは保持領域に比例します。旧状態の破棄費用を加えます。

ソースのAPI注記
mf_graph<Cap=std::int64_t>()/mf_graph(n): 空/n頂点の有向グラフ。Capはbool以外の整数型。O(1)/O(n)。
ACLと同名・同じ呼び出し形式。自己辺・多重辺・逆向きの元辺を追加できる。
add_edge(from,to,cap): 非負容量の元辺を追加し、追加順のint番号を返す。償却O(1)。
edgeは{int from,to;Cap cap,flow;}。get_edge(int id)/edges(): 元辺のコピー/追加順の一覧。O(1)/O(m)。
flow(s,t)/flow(s,t,flow_limit): 型の最大値/非負の指定上限まで追加で流し、追加量を返す。O(n+n²m)、作業領域O(n)。
同じ始点・終点で継続可能。総量がCap上限を越す場合は分けて呼び、累積値を十分広い型で保持する。
min_cut(s): 残余グラフでsから到達可能な頂点のbool配列。O(n+m)時間・O(n)領域。最後まで流した後は最小カット。
get_edge/edges/min_cutはACL形式の非const版に加えて、constオブジェクトからも同名で呼べる。
change_edge(int id,new_cap,new_flow): 指定辺を0<=new_flow<=new_capへ変更。O(1)。流量保存は利用側で保証する。
追加機能: size()/edge_count()は頂点数int/元辺数size_tをO(1)で返す。reserve_edges(m)は位置表を予約。
コピー構築/代入: 残余を独立所有しO(n+m)。移動構築はO(1)、移動元は空。代入は自身への参照を返す。
reset(n=0): O(n+旧領域の破棄)で空のn頂点へ戻す。swap(other)はO(1)。代入にも旧領域の破棄費用が加わる。
ACLのs!=tという制約外では、s==tを追加仕様として0にする。flow_limit==0も0。
反復Dinic法とFIFO push-relabelを切り替える。上限1は経路1本をBFSで探し、O(n+m)。
深い経路も再帰しない。入力検査はSKIP_RUNTIME_CHECKSで除くが、内部添字上限は維持。
get/changeのidは[0,edge_count())。辺数はINT_MAX以下。継続flowで異なる端点を使う場合も流量保存が前提。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
制作進行の宮森あおいです!(一般容量最大流) coverage_graph_capacity_shirobako.cpp 未提出 —
D - Maxflow max_flow_grid.cpp 参考検証・移行先あり AC
Matching on Bipartite Graph (mf_graph) preferred_max_flow_bipartite.cpp 現行未照合・要再提出 AC

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 未測定
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 数学的参考(push-relabel): https://doi.org/10.1145/48014.61051
// 参考(最大流の理論・ACLのAPI): https://atcoder.github.io/ac-library/production/document_ja/maxflow.html
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/max_flow.md
//
// API一覧
// mf_graph<Cap=std::int64_t>()/mf_graph(n): 空/n頂点の有向グラフ。Capはbool以外の整数型。O(1)/O(n)。
// ACLと同名・同じ呼び出し形式。自己辺・多重辺・逆向きの元辺を追加できる。
// add_edge(from,to,cap): 非負容量の元辺を追加し、追加順のint番号を返す。償却O(1)。
// edgeは{int from,to;Cap cap,flow;}。get_edge(int id)/edges(): 元辺のコピー/追加順の一覧。O(1)/O(m)。
// flow(s,t)/flow(s,t,flow_limit): 型の最大値/非負の指定上限まで追加で流し、追加量を返す。O(n+n²m)、作業領域O(n)。
// 同じ始点・終点で継続可能。総量がCap上限を越す場合は分けて呼び、累積値を十分広い型で保持する。
// min_cut(s): 残余グラフでsから到達可能な頂点のbool配列。O(n+m)時間・O(n)領域。最後まで流した後は最小カット。
// get_edge/edges/min_cutはACL形式の非const版に加えて、constオブジェクトからも同名で呼べる。
// change_edge(int id,new_cap,new_flow): 指定辺を0<=new_flow<=new_capへ変更。O(1)。流量保存は利用側で保証する。
// 追加機能: size()/edge_count()は頂点数int/元辺数size_tをO(1)で返す。reserve_edges(m)は位置表を予約。
// コピー構築/代入: 残余を独立所有しO(n+m)。移動構築はO(1)、移動元は空。代入は自身への参照を返す。
// reset(n=0): O(n+旧領域の破棄)で空のn頂点へ戻す。swap(other)はO(1)。代入にも旧領域の破棄費用が加わる。
// ACLのs!=tという制約外では、s==tを追加仕様として0にする。flow_limit==0も0。
// 反復Dinic法とFIFO push-relabelを切り替える。上限1は経路1本をBFSで探し、O(n+m)。
// 深い経路も再帰しない。入力検査はSKIP_RUNTIME_CHECKSで除くが、内部添字上限は維持。
// get/changeのidは[0,edge_count())。辺数はINT_MAX以下。継続flowで異なる端点を使う場合も流量保存が前提。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <new>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_MAX_FLOW_CAPACITY_DEFINED
#define SIRKIT_MAX_FLOW_CAPACITY_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
inline void CheckMaxFlowAppendCapacity(std::size_t edges, std::size_t from_degree,
                                       std::size_t to_degree, bool loop) {
    constexpr auto maximum = static_cast<std::size_t>(std::numeric_limits<int>::max());
    if (edges >= maximum) throw std::length_error("mf_graph: too many edges");
    if (from_degree >= maximum || to_degree >= maximum || (loop && from_degree >= maximum - 1))
        throw std::length_error("mf_graph: too many incident edges");
}

constexpr bool MaxFlowCanUsePreflow(std::size_t vertices) noexcept {
    return vertices < static_cast<std::size_t>(std::numeric_limits<int>::max());
}
}
#endif
#ifndef SIRKIT_MAX_FLOW_DEFINED
#define SIRKIT_MAX_FLOW_DEFINED

template<class Cap = std::int64_t>
class mf_graph {
    static_assert(std::is_integral_v<Cap> && !std::is_same_v<Cap, bool>, "capacity must be a non-bool integer");
public:
    struct edge { int from; int to; Cap cap; Cap flow; };
private:
    struct Arc { int to; int reverse; Cap residual; };
    struct Frame { int vertex; Cap limit; Cap sent; };
    std::vector<std::vector<Arc>> graph_;
    std::vector<std::pair<int, int>> positions_;
    std::vector<int> level_, next_, queue_;
    std::vector<Frame> frames_;
    static std::size_t checked_size(int n) {
        if (n < 0) throw std::length_error("mf_graph: negative vertex count");
        return static_cast<std::size_t>(n);
    }
#ifndef SKIP_RUNTIME_CHECKS
    void vertex(int v) const {
        if (v < 0 || v >= size()) throw std::out_of_range("mf_graph: vertex out of range");
    }
    void edge_id(int id) const {
        if (id < 0 || static_cast<std::size_t>(id) >= positions_.size()) throw std::out_of_range("mf_graph: edge out of range");
    }
    static void nonnegative(Cap value) {
        if constexpr (std::is_signed_v<Cap>) if (value < 0) throw std::invalid_argument("mf_graph: negative capacity");
    }
#endif
    bool levels(int source, int sink) {
        std::fill(level_.begin(), level_.end(), -1);
        int front = 0, end = 0; queue_[end++] = source; level_[source] = 0;
        while (front != end) {
            const int v = queue_[front++];
            for (const auto& edge : graph_[v]) if (edge.residual != 0 && level_[edge.to] == -1) {
                level_[edge.to] = level_[v] + 1;
                // sinkの直前層までは発見済みなので、最短路の辺はDFSで列挙できる。
                if (edge.to == sink) return true;
                queue_[end++] = edge.to;
            }
        }
        return false;
    }
    Cap blocking_flow(int source, int sink, Cap limit) {
        frames_.clear(); frames_.push_back({source, limit, 0});
        for (;;) {
            auto& frame = frames_.back(); const int v = frame.vertex;
            if (v != sink && frame.sent != frame.limit) {
                auto& cursor = next_[v];
                while (cursor != static_cast<int>(graph_[v].size())) {
                    const auto& edge = graph_[v][cursor];
                    if (edge.residual != 0 && level_[edge.to] == level_[v] + 1) break;
                    ++cursor;
                }
                if (cursor != static_cast<int>(graph_[v].size())) {
                    const auto& edge = graph_[v][cursor];
                    frames_.push_back({edge.to, std::min(static_cast<Cap>(frame.limit - frame.sent), edge.residual), 0});
                    continue;
                }
                level_[v] = -1;
            }
            const Cap sent = v == sink ? frame.limit : frame.sent;
            frames_.pop_back();
            if (frames_.empty()) return sent;
            auto& parent = frames_.back(); auto& edge = graph_[parent.vertex][next_[parent.vertex]];
            edge.residual -= sent; graph_[edge.to][edge.reverse].residual += sent;
            parent.sent += sent;
            if (edge.residual == 0 || level_[edge.to] == -1) ++next_[parent.vertex];
        }
    }
    Cap unit_flow(int source, int sink) {
        std::fill(level_.begin(), level_.end(), -1);
        int front = 0, tail = 0;
        queue_[tail++] = source;
        level_[source] = source;
        while (front != tail) {
            const int v = queue_[front++];
            for (int index = 0; index != static_cast<int>(graph_[v].size()); ++index) {
                const auto& edge = graph_[v][index];
                const int u = edge.to;
                if (edge.residual == 0 || level_[u] != -1) continue;
                level_[u] = v;
                next_[u] = index;
                if (u == sink) {
                    for (int to = sink; to != source; to = level_[to]) {
                        auto& arc = graph_[level_[to]][next_[to]];
                        --arc.residual;
                        ++graph_[to][arc.reverse].residual;
                    }
                    return Cap{1};
                }
                queue_[tail++] = u;
            }
        }
        return Cap{0};
    }
    Cap preflow(int source, int sink, Cap limit) {
        const std::size_t n = graph_.size();
        const std::uint32_t virtual_height = static_cast<std::uint32_t>(n + 1);
        constexpr std::uint32_t unseen = std::numeric_limits<std::uint32_t>::max();
        // 確保失敗時は、残余を変更する前に退出する。
        std::vector<std::uint32_t> height(n);
        std::vector<Cap> excess(n, Cap{0});
        std::vector<int> cursor(n, 0), fifo(n);
        std::vector<unsigned char> active(n, 0);
        std::size_t front = 0, back = 0, count = 0;
        auto enqueue = [&](int v) {
            if (v == sink || active[v] || excess[v] == 0) return;
            active[v] = 1;
            fifo[back] = v;
            if (++back == n) back = 0;
            ++count;
        };
        auto relabel_all = [&] {
            // activeは再構築中だけBFSの訪問印として使う。
            std::fill(active.begin(), active.end(), 0);
            auto assign_height = [&](int v, std::uint32_t value) {
                if (height[v] != value) cursor[v] = 0;
                height[v] = value;
                active[v] = 1;
            };
            int head = 0, tail = 0;
            queue_[tail++] = sink;
            assign_height(sink, 0);
            while (head != tail) {
                const int v = queue_[head++];
                for (const auto& edge : graph_[v]) {
                    const int u = edge.to;
                    if (!active[u] && graph_[u][edge.reverse].residual != 0) {
                        assign_height(u, height[v] + 1);
                        queue_[tail++] = u;
                    }
                }
            }
            // tへ届かない余剰も、s経由で仮想始点へ戻して流量保存を回復する。
            if (!active[source]) {
                head = tail = 0;
                assign_height(source, virtual_height + 1);
                queue_[tail++] = source;
                while (head != tail) {
                    const int v = queue_[head++];
                    for (const auto& edge : graph_[v]) {
                        const int u = edge.to;
                        if (!active[u] && graph_[u][edge.reverse].residual != 0) {
                            assign_height(u, height[v] + 1);
                            queue_[tail++] = u;
                        }
                    }
                }
            }
            for (std::size_t v = 0; v < n; ++v) {
                if (!active[v] && height[v] != unseen) {
                    height[v] = unseen;
                    cursor[v] = 0;
                }
                active[v] = 0;
            }
            front = back = count = 0;
            for (int v = 0; v < static_cast<int>(n); ++v) enqueue(v);
        };
        excess[source] = limit;
        relabel_all();
        std::uint64_t work = 0;
        const std::uint64_t budget = static_cast<std::uint64_t>(positions_.size()) + n;
        while (count != 0) {
            const int v = fifo[front];
            if (++front == n) front = 0;
            --count;
            active[v] = 0;
            for (;;) {
                if (v == source && height[v] >= virtual_height + 1) {
                    // 容量limitの暗黙の逆辺で、未使用予算を返す。
                    excess[v] = 0;
                    break;
                }
                const int degree = static_cast<int>(graph_[v].size());
                int& index = cursor[v];
                while (index != degree) {
                    auto& edge = graph_[v][index];
                    ++work;
                    if (edge.residual != 0 && height[edge.to] != unseen &&
                        height[v] == height[edge.to] + 1) {
                        const Cap amount = std::min(excess[v], edge.residual);
                        edge.residual -= amount;
                        graph_[edge.to][edge.reverse].residual += amount;
                        excess[v] -= amount;
                        excess[edge.to] += amount;
                        enqueue(edge.to);
                        if (excess[v] == 0) break;
                    }
                    ++index;
                }
                if (excess[v] == 0) break;
                std::uint32_t best = v == source ? virtual_height : unseen;
                for (const auto& edge : graph_[v]) {
                    if (edge.residual != 0) best = std::min(best, height[edge.to]);
                }
                work += graph_[v].size();
                // 正の余剰には、流した経路の逆辺で仮想始点へ戻る経路が必ずある。
                height[v] = best + 1;
                index = 0;
                if (work >= budget) break;
            }
            if (work >= budget) {
                relabel_all();
                work = 0;
            }
        }
        return excess[sink];
    }
public:
    mf_graph() = default;
    explicit mf_graph(int n) : graph_(checked_size(n)), level_(graph_.size()), next_(graph_.size()), queue_(graph_.size()) {}
    mf_graph(const mf_graph&) = default;
    mf_graph(mf_graph&& other) noexcept { swap(other); }
    mf_graph& operator=(mf_graph other) noexcept { swap(other); return *this; }
    void swap(mf_graph& other) noexcept {
        graph_.swap(other.graph_); positions_.swap(other.positions_); level_.swap(other.level_);
        next_.swap(other.next_); queue_.swap(other.queue_); frames_.swap(other.frames_);
    }
    void reset(int n = 0) { mf_graph replacement(n); swap(replacement); }
    int size() const noexcept { return static_cast<int>(graph_.size()); }
    std::size_t edge_count() const noexcept { return positions_.size(); }
    void reserve_edges(std::size_t count) {
        if (count > static_cast<std::size_t>(std::numeric_limits<int>::max()))
            throw std::length_error("mf_graph: too many edges");
        positions_.reserve(count);
    }
    int add_edge(int from, int to, Cap capacity) {
#ifndef SKIP_RUNTIME_CHECKS
        vertex(from); vertex(to); nonnegative(capacity);
#endif
        /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::CheckMaxFlowAppendCapacity(
            positions_.size(), graph_[from].size(), graph_[to].size(), from == to);
        const int forward = static_cast<int>(graph_[from].size());
        const int backward = static_cast<int>(graph_[to].size()) + static_cast<int>(from == to);
        graph_[from].push_back({to, backward, capacity});
        try { graph_[to].push_back({from, forward, 0}); }
        catch (...) { graph_[from].pop_back(); throw; }
        try { positions_.emplace_back(from, forward); }
        catch (...) { graph_[to].pop_back(); graph_[from].pop_back(); throw; }
        return static_cast<int>(positions_.size()) - 1;
    }
    edge get_edge(int id) { return std::as_const(*this).get_edge(id); }
    edge get_edge(int id) const {
#ifndef SKIP_RUNTIME_CHECKS
        edge_id(id);
#endif
        const auto [from, position] = positions_[id]; const auto& edge = graph_[from][position];
        const Cap sent = graph_[edge.to][edge.reverse].residual;
        return {from, edge.to, static_cast<Cap>(edge.residual + sent), sent};
    }
    std::vector<edge> edges() { return std::as_const(*this).edges(); }
    std::vector<edge> edges() const {
        std::vector<edge> result; result.reserve(positions_.size());
        for (int id = 0; id < static_cast<int>(positions_.size()); ++id) result.push_back(get_edge(id));
        return result;
    }
    void change_edge(int id, Cap capacity, Cap sent) {
#ifndef SKIP_RUNTIME_CHECKS
        edge_id(id); nonnegative(capacity); nonnegative(sent);
        if (sent > capacity) throw std::invalid_argument("mf_graph: flow exceeds capacity");
#endif
        const auto [from, position] = positions_[id]; auto& edge = graph_[from][position];
        edge.residual = capacity - sent; graph_[edge.to][edge.reverse].residual = sent;
    }
    Cap flow(int source, int sink) { return flow(source, sink, std::numeric_limits<Cap>::max()); }
    Cap flow(int source, int sink, Cap limit) {
#ifndef SKIP_RUNTIME_CHECKS
        vertex(source); vertex(sink); nonnegative(limit);
#endif
        if (source == sink || limit == 0) return 0;
        if (limit == Cap{1}) return unit_flow(source, sink);
        frames_.reserve(graph_.size());
        Cap result = 0;
        int phases = 0;
        // 最大頂点数では高さの上限と未発見印が同じ値になるため、Dinicを続ける。
        bool allow_preflow = /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::MaxFlowCanUsePreflow(graph_.size());
        while (result != limit && levels(source, sink)) {
            if (allow_preflow && phases >= 4) {
                try { return result + preflow(source, sink, static_cast<Cap>(limit - result)); }
                catch (const std::bad_alloc&) { allow_preflow = false; }
            }
            std::fill(next_.begin(), next_.end(), 0);
            result += blocking_flow(source, sink, static_cast<Cap>(limit - result));
            ++phases;
        }
        return result;
    }
    std::vector<bool> min_cut(int source) { return std::as_const(*this).min_cut(source); }
    std::vector<bool> min_cut(int source) const {
#ifndef SKIP_RUNTIME_CHECKS
        vertex(source);
#endif
        std::vector<bool> reachable(graph_.size()); std::vector<int> queue;
        queue.reserve(graph_.size()); queue.push_back(source); reachable[source] = true;
        for (std::size_t front = 0; front < queue.size(); ++front) {
            const int v = queue[front];
            for (const auto& edge : graph_[v]) if (edge.residual != 0 && !reachable[edge.to]) {
                reachable[edge.to] = true; queue.push_back(edge.to);
            }
        }
        return reachable;
    }
};
#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page