Pagini recente » Cod sursa (job #261373) | Cod sursa (job #1915948) | Cod sursa (job #1057532) | Cod sursa (job #1209069) | Cod sursa (job #2954938)
#include <iostream>
#include <limits.h>
#include <queue>
#include <string.h>
#include <fstream>
using namespace std;
int n,m,val,i,graph[1005][5005],x,y;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
bool bfs(int rGraph[1005][5005],int n, int s, int t, int parent[])
{
bool visited[n];
memset(visited, 0, sizeof(visited));
queue<int> q;
q.push(s);
visited[s] = true;
parent[s] = -1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v = 1; v <=n; v++) {
if (visited[v] == false && rGraph[u][v] > 0) {
if (v == t) {
parent[v] = u;
return true;
}
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
}
return false;
}
int fordFulkerson(int graph[1005][5005],int n, int s, int t)
{
int u, v;
int rGraph[1005][5005];
for (u = 1; u <=n; u++)
for (v = 1; v <=n; v++)
rGraph[u][v] = graph[u][v];
int parent[n];
int max_flow = 0; // There is no flow initially
while (bfs(rGraph,n, s, t, parent)) {
int path_flow = INT_MAX;
for (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;
}
max_flow += path_flow;
}
return max_flow;
}
int main()
{
fin>>n>>m;
for(i=1;i<=m;i++)
{
fin>>x>>y>>val;
graph[x][y]=val;
}
//"The maximum possible flow is "
fout << fordFulkerson(graph,n, 1, n);
return 0;
}