Pagini recente » Cod sursa (job #2708568) | Cod sursa (job #2119082) | Cod sursa (job #758310) | Cod sursa (job #2676701) | Cod sursa (job #1169790)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stdlib.h>
using namespace std;
ifstream fi ("maxflow.in");
ofstream fo ("maxflow.out");
const int dim = 1005;
const int OO = (1<<31) - 1;
int N, M, source, sink;
int C[dim][dim], F[dim][dim];
vector <int> V[dim];
void read ()
{
fi >> N >> M;
for (int i = 1, x, y, z; i <= M; i++)
{
fi >> x >> y >> z;
C[x][y] = z;
V[x].push_back (y);
V[y].push_back (x);
}
source = 1;
sink = N;
}
bool bfs (int P[], int D[], int &m)
{
int n, v, i;
queue <int> Q;
Q.push (source);
for (i = 1; i <= N; i++)
{
P[i] = 0;
D[i] = OO;
}
P[source] = -1;
while (!Q.empty())
{
n = Q.front ();
Q.pop ();
for (i = 0; i < V[n].size(); i++)
{
v = V[n][i];
if (C[n][v] - F[n][v] > 0 && P[v] == 0)
{
P[v] = n;
D[v] = min (D[n], C[n][v] - F[n][v]);
if (v == sink)
{
m = D[sink];
return true;
}
Q.push (v);
}
}
}
return false;
}
void edmonds_karp ()
{
int *P = (int *) malloc (sizeof (int) * (N+1));
int *D = (int *) malloc (sizeof (int) * (N+1));
int m, n, p;
int flow = 0;
while (bfs (P, D, m))
{
for (n = sink, p = P[sink]; n != source; n = P[n], p = P[p])
{
F[p][n] += m;
F[n][p] -= m;
}
}
for (int i = 0; i < V[source].size(); i++)
{
flow += F[source][V[source][i]];
}
fo << flow << '\n';
}
int main()
{
read ();
edmonds_karp ();
return 0;
}