Pagini recente » Cod sursa (job #1276766) | Cod sursa (job #2674152) | Cod sursa (job #977150) | Cod sursa (job #1626444) | Cod sursa (job #1388139)
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int MAX_N = 1000, MAX_M = 5000, INF = MAX_M*110000;
FILE *in, *out;
int lst[MAX_N+1], urm[2*MAX_M+1], vf[2*MAX_M+1];
int nrg;
int c[MAX_N+1][MAX_N+1], f[MAX_N+1][MAX_N+1];
int m, n;
void add(int x, int y, int cap)
{
nrg++;
urm[nrg] = lst[x];
vf[nrg] = y;
c[x][y] += cap;
lst[x] = nrg;
}
queue<int> q;
int t[MAX_N+1];
bool viz[MAX_N+1];
bool bfs()
{
q.push(1);
memset(viz, false, sizeof(viz));
viz[1] = true;
int x;
int p;
while(!q.empty())
{
x = q.front();
q.pop();
p = lst[x];
if(x != n)
{
while(p != 0)
{
int y = vf[p];
p = urm[p];
if(viz[y] || c[x][y]==f[x][y]) continue;
viz[y] = true;
q.push(y);
t[y] = x;
}
}
}
return viz[n];
}
int fmin;
int minim(int a, int b)
{
return (a<b)?a:b;
}
int main()
{
in = fopen("maxflow.in", "r");
out = fopen("maxflow.out", "w");
int x, y, cap;
fscanf(in, "%d%d", &n, &m);
for(int i = 0; i < m; i++)
{
fscanf(in,"%d%d%d", &x, &y, &cap);
add(x,y,cap);
add(y,x,0);
}
int flow = 0;
while(bfs() == true)
{
int p = lst[n];
while(p != 0)
{
int y = vf[p];
p = urm[p];
if(!viz[y] || c[y][n] == f[y][n]) continue;
t[n] = y;
fmin = INF;
for(int nod = n; nod != 1; nod = t[nod])
fmin = minim(fmin, c[t[nod]][nod]-f[t[nod]][nod]);
if(fmin != 0)
{
for(int nod = n; nod != 1; nod = t[nod])
{
f[t[nod]][nod] += fmin;
f[nod][t[nod]] -= fmin;
}
flow += fmin;
}
// p = urm[p];
}
}
fprintf(out, "%d", flow);
fclose(in);
fclose(out);
return 0;
}