Pagini recente » Cod sursa (job #2782495) | Cod sursa (job #1352620) | Cod sursa (job #1400019) | Cod sursa (job #2389613) | Cod sursa (job #1409192)
#include <fstream>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
fstream f("maxflow.in", ios::in);
fstream g("maxflow.out", ios::out);
const int nmax = 1010;
const int INF = 0x3f3f3f3f;
vector <int> a[nmax];
int t[nmax], viz[nmax], c[nmax][nmax];
int n, m, i, fmin, flow;
void read()
{
int x, y, cost;
f >> n >> m;
for (i = 1; i <= m; i++)
{
f >> x >> y >> cost;
a[x].push_back(y);
a[y].push_back(x);
c[x][y] = cost;
}
}
int tree()
{
int nc;
memset(viz, 0, sizeof(viz));
memset(t, 0, sizeof(t));
queue <int> q;
q.push(1);
t[1] = 1;
viz[1] = 1;
while (!q.empty())
{
nc = q.front(); q.pop();
for (vector<int>::iterator it = a[nc].begin(); it != a[nc].end(); ++it)
if ((c[nc][*it] != 0) && (!viz[*it]))
{
viz[*it] = 1;
if (*it != n)
{
t[*it] = nc;
q.push(*it);
}
}
}
return viz[n];
}
void solve()
{
int x, y, nc;
while (tree())
{
for (vector <int>::iterator it = a[n].begin(); it != a[n].end(); ++it)
if ((c[*it][n] != 0) && (viz[*it]))
{
t[n] = *it;
fmin = INF;
nc = n;
while (nc != 1)
{
x = t[nc]; y = nc;
if (c[x][y] < fmin) fmin = c[x][y];
nc = t[nc];
}
flow += fmin;
if (fmin > 0)
{
nc = n;
while (nc != 1)
{
x = t[nc]; y = nc;
c[x][y] -= fmin;
c[y][x] += fmin;
nc = t[nc];
}
}
}
}
}
int main()
{
read();
solve();
g << flow;
return 0;
}