//
// main.cpp
// Ford-Fulkerson with capacity scaling
//
// Created by Longxiang Lyu on 8/9/16.
// Copyright (c) 2016 Longxiang Lyu. All rights reserved.
//
#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 delta)
{
int V = 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] >= delta)
{
q.push(v);
parent[v] = u;
visited[v] = 1;
}
}
}
return visited[t] == 1;
}
int getDelta(vector<vector<int>> &graph)
{
int maxC = 0;
int delta = 1;
// get the max capacity
for (auto it = graph.cbegin(); it != graph.cend(); ++it)
maxC = max(maxC, *max_element(it->cbegin(), it->cend()));
while ((delta *= 2) <= maxC);
return delta / 2;
}
int fordFulkerson(vector<vector<int>> &graph, int s, int t)
{
int u, v;
int delta;
vector<vector<int>> rGraph = graph;
delta = getDelta(graph);
vector<int> parent;
int max_flow = 0; // initially zero flow
while (delta >= 1)
{
while (bfs(rGraph, parent, s, t, delta))
{
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, rGraph[u][v]);
}
for (v = t; v != s; v = parent[v])
{
u = parent[v];
rGraph[u][v] -= bottleneck;
rGraph[v][u] += bottleneck;
}
max_flow += bottleneck;
}
delta /= 2;
}
return max_flow;
}
int main(int argc, const char * argv[])
{
// insert code here...
vector<vector<int>> graph = { {0, 16, 13, 0, 0, 0}, {0, 0, 10, 12, 0, 0}, {0, 4, 0, 0, 14, 0}, {0, 0, 9, 0, 0, 20}, {0, 0, 0, 7, 0, 4}, {0, 0, 0, 0, 0, 0}};
cout << "The maximum possible flow is " << fordFulkerson(graph, 0, 5) << endl;
vector<vector<int>> graph2 = {{0, 110, 102, 0}, {0, 0, 1, 122}, {0, 0, 0, 170}, {0, 0, 0, 0}};
cout << "The maximum possible flow is " << fordFulkerson(graph2, 0, 3) << endl;
return 0;
}
This capacity algorithm is proved to run in O(m*m*logC) time complexity, C is the maximum edge capacity. Prove could be found in slide from Princeton in the first reference.
Reference:
http://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/07NetworkFlowI-2x2.pdf
http://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/