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