Алгоритм Форда-Фалкерсона
Перейти к навигации
Перейти к поиску
class Graph { struct Edge { int a, b, capacity, flow; Edge(int a, int b, int capacity) : a(a), b(b), capacity(capacity), flow(0) {} int other(int v) const { return v == a ? b : a; } int capacityTo(int v) const { return v == b ? capacity - flow : flow; } void addFlowTo(int v, int f) { flow += (v == b ? f : -f); } }; vector<Edge> edges; vector<vector<int>> g; vector<bool> visited; vector<int> edgeTo; void dfs(int v) { visited[v] = 1; for (int e : g[v]) { int to = edges[e].other(v); if (!visited[to] && edges[e].capacityTo(to) > 0) { edgeTo[to] = e; dfs(to); } } } bool hasPath(int from, int to) { fill(visited.begin(), visited.end(), 0); dfs(from); return visited[to]; } int bottleneckCapacity(int from, int to) { int bCapacity = 1e9; for (int v = to; v != from; v = edges[edgeTo[v]].other(v)) bCapacity = min(bCapacity, edges[edgeTo[v]].capacityTo(v)); return bCapacity; } void addFlow(int from, int to, int flow) { for (int v = to; v != from; v = edges[edgeTo[v]].other(v)) edges[edgeTo[v]].addFlowTo(v, flow); } public: Graph(int vertexCount) { g.resize(vertexCount); visited.resize(vertexCount); edgeTo.resize(vertexCount); } void addEdge(int from, int to, int capacity) { edges.push_back(Edge(from, to, capacity)); g[from].push_back(edges.size() - 1); g[to].push_back(edges.size() - 1); } long long maxFlow(int from, int to) { long long flow = 0; while (hasPath(from, to)) { int deltaFlow = bottleneckCapacity(from, to); addFlow(from, to, deltaFlow); flow += deltaFlow; } return flow; } };
Ссылки
Теория:
- algs4.cs.princeton.edu — 6.4 Maximum Flow
- neerc.ifmo.ru/wiki — Алгоритм Форда-Фалкерсона
- Brilliant.org — Ford-Fulkerson Algorithm
Демонстрация:
Код:
- CodeLibrary — Maximum flow. Ford-Fulkerson alogithm in O(V^2 * FLOW)
- Algos — Ford-Fulkerson maxflow
- algs4.cs.princeton.edu/code — capacitated edge with flow, capacitated network, maxflow–mincut (несмотря на название, используется алгоритм Эдмондса-Карпа)
Задачи: