Pagini recente » Cod sursa (job #2378649) | Cod sursa (job #861962) | Cod sursa (job #879884) | Cod sursa (job #581721) | Cod sursa (job #2954965)
#include <iostream>
#include <limits.h>
#include <queue>
#include <string.h>
#include <fstream>
using namespace std;
int n,m,val,i,cost[1001][1001],x,y;
vector<vector<int>> adj(1001);
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
bool bfs(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;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto v: adj[u]) {
if (visited[v] == false && cost[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 n, int s, int t)
{
int u, v;
int parent[n];
int max_flow = 0;
while (bfs(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, cost[u][v]);
}
for (v = t; v != s; v = parent[v]) {
u = parent[v];
cost[u][v] -= path_flow;
cost[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
int main()
{
fin>>n>>m;
for(i=1;i<=m;i++)
{
fin>>x>>y>>val;
adj[x].push_back(y);
adj[y].push_back(x);
cost[x][y]=val;
}
//"The maximum possible flow is "
fout << fordFulkerson(n, 1, n);
return 0;
}