Pagini recente » Cod sursa (job #606283) | Cod sursa (job #2360258) | Monitorul de evaluare | Cod sursa (job #3138173) | Cod sursa (job #3036560)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int M = 5002;
const int N = 1002;
const int INF = 110002;
int n, m, s, t;
int pred[N];
vector<int> a[N];
int cap[N][N];
int bfs()
{
for(int i=1; i<=n; i++)
pred[i]=-1;
pred[s]=-2;
queue<pair<int, int>> q;
q.push({s, INF});
while(!q.empty()){
int x=q.front().first;
int cost = q.front().second;
q.pop();
for(auto y: a[x])
{
if(pred[y] == -1 && cap[x][y])
{
pred[y] = x;
int newflow = min(cost, cap[x][y]);
if(y == t)
return newflow;
q.push({y, newflow});
}
}
}
return 0;
}
int maxflow()
{
int totalflow = 0;
int newflow;
while(newflow = bfs()){
totalflow +=newflow;
int y = t;
while(y!=s){
int x=pred[y];
cap[x][y]-=newflow;
cap[y][x]+=newflow;
y=x;
}
}
return totalflow;
}
int main()
{
in>>n>>m;
s=1; t=n;
for(int i=1; i<=m; i++)
{
int x, y;
in>>x>>y;
a[x].push_back(y);
a[y].push_back(x);
in>>cap[x][y];
}
out<<maxflow();
return 0;
}