Pagini recente » Cod sursa (job #2054935) | Cod sursa (job #1994275) | Cod sursa (job #1631928) | Cod sursa (job #2478481) | Cod sursa (job #3184698)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int const nMax = 1000+5;
int const flowMax = 110000 + 5;
int n, m, x, y, cap;
struct nod{
int fMax, fSent;
}a;
vector <vector<nod>> graph(nMax, vector<nod>(nMax,{0,0}));
int findCostPath(){
vector <int> f(n+2, 0);
vector <bool> viz(n+2, false);
queue <int> q;
bool ok = false;
q.push(1);
viz[1] = true;
while (!q.empty())
{
int x = q.front();
q.pop();
for(int i = 1; i <n; i++){
if(!viz[i]){
if(graph[x][i].fMax - graph[x][i].fSent > 0){
q.push(i);
viz[i] = true;
f[i] = x;
}
}
}
for(int i = 1; i <n; i++){
if(!viz[i]){
if(graph[i][x].fSent > 0){
q.push(i);
viz[i] = true;
f[i] = -x;
}
}
}
if(graph[x][n].fMax - graph[x][n].fSent > 0){
f[n] = x;
ok = true;
break;
}
if(graph[n][x].fSent > 0){
f[n] = -x;
ok = true;
break;
}
}
if(ok){
int x = n;
int ans = flowMax;
while (x != 1)
{
int dad = abs(f[x]);
bool invers = f[x] < 0;
if(invers)
ans = min(ans, graph[dad][x].fSent);
else
ans = min(ans, graph[dad][x].fMax - graph[dad][x].fSent);
x = dad;
}
x = n;
while (x != 1)
{
int dad = abs(f[x]);
bool invers = f[x] < 0;
if(invers)
graph[x][dad].fSent -= ans;
else
graph[dad][x].fSent += ans;
x = dad;
}
return ans;
}
return 0;
}
int fluxMax(){
int maxPush = 0;
int ans = 0;
do
{
maxPush = findCostPath();
ans += maxPush;
} while (maxPush);
return ans;
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++){
fin >> x >> y >> cap;
graph[x][y] = {cap, 0};
}
fout << fluxMax();
return 0;
}