Pagini recente » Cod sursa (job #2833484) | Cod sursa (job #2077231) | Cod sursa (job #2351143) | Cod sursa (job #2011928) | Cod sursa (job #2973764)
//ford fulkerson algorithm
//time complexity of O(max_flow*E)
#include <fstream>
#include <vector>
#include <queue>
#include <iostream>
#define NMAX (1 << 31) - 1
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
static int n;
//check if there is a path in residual graph from source(S) to sink(T)
bool bfs(const vector<vector<int>>& rgraph, int s, int t, vector<int>& parent){
vector<bool> viz(n+1, false);
queue<int> Q;
Q.push(s);
viz[s] = true;
parent[s] = -1;
while(!Q.empty()){
int u = Q.front();
Q.pop();
for(int v = 1; v <= n; v++){
if(viz[v] == false && rgraph[u][v] > 0){
if(v == t){
parent[v] = u;
return true;
}
Q.push(v);
parent[v] = u;
viz[v] = true;
}
}
}
return false;
}
//maximum flow between s and t
int fordFulkerson(const vector<vector<int>>& graph, int s, int t){
int u, v;
vector<vector<int>> rgraph(n+1, vector<int>(n+1, 0));
for(int u = 1; u <= n; u++){
for(int v = 1; v <= n; v++){
rgraph[u][v] = graph[u][v];
}
}
vector<int> parent(n+1, -1);
int max_flow = 0;
while(bfs(rgraph, s, t, parent)){
int path_flow = NMAX;
for(int v = t; v != s; v = parent[v]){
u = parent[v];
path_flow = min(path_flow, rgraph[u][v]);
}
for(v = t; v != s; v = parent[v]){
u = parent[v];
rgraph[u][v] -= path_flow;
rgraph[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
int main(){
fin >> n;
vector<vector<int>> graph(n+1, vector<int> (n+1, 0));
int m;
fin >> m;
for(int i = 1; i <= m; i++){
int x, y, capacity;
fin >> x >> y >> capacity;
graph[x][y] = capacity;
}
fout << fordFulkerson(graph, 1, n);
}