Maximum Flow
A Edmonds-Karp
Code
t i m e : O ( V ∗ E 2 ) time: O(V*E^2) time:O(V∗E2)
/*
* @Descripttion: Edmonds-Karp
* @version: 1.0
* @Author: pineklll
* @Date: 2022-03-24 13:56:09
* @LastEditors: pineklll
* @LastEditTime: 2022-03-24 14:28:00
*/
#include <bits\stdc++.h>
const int INF = 1e9;
const int maxn = 300;
int n, m,
// the graph and the residual graph all together
graph[maxn][maxn],
// if we have visited the vec, in the meantime record the path
pre[maxn];
/**
* @brief BFS(not efficient using DFS)
*
* @param s source point
* @param t target point
* @return int the maximum capacity along the path
*/
int bfs(int s, int t){
int flow[maxn];
memset(pre, -1, sizeof pre);
// cause we wanna take the minimum value
flow[s] = INF;
pre[s] = 0;
std::queue<int> Q;
Q.push(s);
while(!Q.empty()){
int fr = Q.front();
Q.pop();
// until we reach the end
if(fr==t)
break;
for (int i = 1; i <= m; i++){
// not the source point, left some flow, and haven't visited yet
if (i != s && graph[fr][i] > 0 && pre[i] == -1){
pre[i] = fr;
Q.push(i);
// record the maximum flow on the path
flow[i] = std::min(flow[fr], graph[fr][i]);
}
}
}
if(pre[t]==-1)
return -1;
return flow[t];
}
/**
* @brief figure out the MaxFlow --- O(V*E^2)
*
* @param s source point
* @param t target point
* @return int maxflow
*/
int maxflow(int s, int t){
int Maxflow = 0;
while(1){
int flow = bfs(s, t);
if (flow == -1)
break;
// update the graph
int cur = t;
while (cur != s){
int father = pre[cur];
// for residual graph
graph[father][cur] -= flow;
graph[cur][father] += flow;
cur = father;
}
Maxflow += flow;
}
return Maxflow;
}