Skip to content

Instantly share code, notes, and snippets.

@jiunbae
Created November 28, 2015 19:47
Show Gist options
  • Save jiunbae/d6f1dec0fe3965c2f71b to your computer and use it in GitHub Desktop.
Save jiunbae/d6f1dec0fe3965c2f71b to your computer and use it in GitHub Desktop.
int MaximumFlow(const graph& g, int s, int t)
{
//maximum flow == return value
int maxflow = 0;
//res is Residual graph
vector<vector<int>> res(g.flow.begin(), g.flow.end());
//parent present where from
vector<int> parent(g.V, -1);
//bfs function for search route
function<bool(int, int)> bfs = [&](int s, int t)->bool{
//queue for bfs
queue<int> qu;
//visited check
vector<bool> visited(g.V, false);
//visit function for visit [add queue, visit check, parent check]
function<void(int, int)> visit = [&](int v, int u)->void {
qu.push(v);
visited[v] = true;
parent[v] = u;
};
visit(s, -1);
while (qu.size())
{
int n = qu.front(); qu.pop();
//for loop n to v
for (size_t v = 0; v < g.V; v++)
if (!visited[v] && res[n][v] > 0)
visit(v, n);
}
return visited[t] == true;
};
//bfs loop, if (s to t) is true
while (bfs(s, t))
{
//init pathflow INF, for renewal
int pathflow = INF;
//renewal pathflow
for (size_t v = t; v != s; v = parent[v])
pathflow = min(pathflow, res[parent[v]][v]);
for (size_t v = t; v != s; v = parent[v])
{
res[parent[v]][v] -= pathflow;
res[v][parent[v]] += pathflow;
}
//add pathflow to maxflow
maxflow += pathflow;
}
if (!print)
{
vector<size_t> out;
for (size_t v = t; v + 1;v = parent[v])
out.push_back(v);
vector<size_t> rout(out.rbegin(), out.rend());
for (size_t t : rout)
cout << t << "->";
cout << endl;
print = true;
}
//return maxflow
return maxflow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment