//
// main.cpp
// MinCut
//
// Created by Longxiang Lyu on 8/15/16.
// Copyright © 2016 Longxiang Lyu. All rights reserved.
// steps to find min-cut
// 1. run ford-fulkerson and consider final residual graph
// 2. all vertex that are reachable from s are in set A
// 3. all vertex that are not reachable from s are in set B
// 4. (A, B) is the min-cut
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
bool bfs(vector<vector<int>> &rGraph, vector<int> &parent, int s, int t)
{
int V = static_cast<int>(rGraph.size());
vector<int> visited(V, 0); // mark all vertices as unvisited
queue<int> q;
q.push(s);
visited[s] = 1; // mark source vertex as visited
parent.clear();
parent.resize(V);
parent[s] = -1;
while (!q.empty())
{
int u = q.front(); // get the first element
q.pop();
for (int v = 0; v != V; ++v)
{
if (visited[v] == 0 && rGraph[u][v] > 0)
{
q.push(v);
parent[v] = u;
visited[v] = 1;
}
}
}
return visited[t] == 1;
}
int fordFulkerson(vector<vector<int>> &graph, int s, int t)
{
int u, v;
vector<int> parent;
int max_flow = 0; // initially zero flow
while (bfs(graph, parent, s, t))
{
int bottleneck = INT_MAX;
// get the bottleneck capacity of the augment path
for (v = t; v != s; v = parent[v])
{
u = parent[v];
bottleneck = min(bottleneck, graph[u][v]);
}
for (v = t; v != s; v = parent[v])
{
u = parent[v];
graph[u][v] -= bottleneck;
graph[v][u] += bottleneck;
}
max_flow += bottleneck;
}
return max_flow;
}
void minCut(const vector<vector<int>> &rGraph, vector<int> &A, int s, int t)
{
// just use breadth search to find reachable nodes in final residual graph.
int V = static_cast<int>(rGraph.size());
queue<int> q;
q.push(s);
A.clear();
A.push_back(s); // mark source vertex in A
while (!q.empty())
{
int u = q.front(); // get the first element
q.pop();
for (int v = 0; v != V; ++v)
{
if (find(A.cbegin(), A.cend(), v) == A.cend() && rGraph[u][v] > 0)
{
q.push(v);
A.push_back(v);
}
}
}
}
template<typename T>
void printV(const vector<T> &arry)
{
for (const T &a : arry)
cout << a << " ";
}
int main(int argc, const char * argv[])
{
// insert code here...
vector<vector<int>> graph = {{0, 10, 10, 0, 0, 0},
{0, 0, 2, 4, 8, 0},
{0, 0, 0, 0, 9, 0},
{0, 0, 0, 0, 0, 10},
{0, 0, 0, 6, 0, 10},
{0, 0, 0, 0, 0, 0}};
cout << "cap(A, B) = " << fordFulkerson(graph, 0, 5) << endl;
vector<int> A;
minCut(graph, A, 0, 5);
cout << "Subset A: ";
printV(A);
cout << endl;
cout << "Subset B: ";
for (int i = 0; i != graph.size(); ++i)
if (find(A.cbegin(), A.cend(), i) == A.cend())
cout << i << " ";
cout << endl;
return 0;
}
Find minimum cut
最新推荐文章于 2018-08-30 00:37:34 发布