Pagini recente » Cod sursa (job #1919063) | Cod sursa (job #395875) | Cod sursa (job #17649) | Cod sursa (job #748560) | Cod sursa (job #3042118)
#include <bits/stdc++.h>
#define NMAX 1008
using namespace std;
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
int n, m, flow, nivel[NMAX];
bool viz[NMAX], dead_end[NMAX];
map < pair <int, int>, int> h;
vector <int> G[NMAX];
int DFS(int nod, int minim);
void nivelare();
int main()
{
int x, y, z;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> z;
G[x].push_back(y);
h[{x,y}] = z;
if (!h[{y,x}])
G[y].push_back(x);
}
x = 1;
nivelare();
while (1)
{
x = 1;
bool ok = 0;
while (x)
{
for (int i = 1; i <= n; i++) viz[i] = 0;
x = DFS(1, INT_MAX);
if (x) ok = 1;
flow += x;
}
if (ok == 0)
break;
nivelare();
}
fout << flow;
return 0;
}
void nivelare()
{
queue <int> Q;
for (int i = 1; i <= n; i++) {viz[i] = 0; dead_end[i] = 0;}
nivel[1] = 0;
viz[1] = 1;
Q.push(1);
while (!Q.empty())
{
int nod = Q.front();
Q.pop();
for (auto el : G[nod])
if (viz[el] == 0 && h[{nod, el}])
{
nivel[el] = nivel[nod] + 1;
Q.push(el);
viz[el] = 1;
}
}
}
int DFS(int nod, int minim)
{
if (nod == n)
return minim;
for (auto el : G[nod])
if (!dead_end[el] && nivel[el] == nivel[nod] + 1 && h[{nod, el}])
{
int x = DFS(el, min(minim, h[{nod ,el}]));
if (x > 0)
{
h[{nod, el}] -= x;
h[{el, nod}] += x;
return x;
}
else
dead_end[el] = 1;
}
return 0;
}