Pagini recente » Cod sursa (job #1276008) | Cod sursa (job #1467504) | Cod sursa (job #3274879) | Cod sursa (job #2902591) | Cod sursa (job #1462675)
#include <iostream>
#include <fstream>
#include <assert.h>
#include <list>
#include <queue>
#include <bitset>
#include <cstring>
#define min(a,b) ((a)<(b))?(a):(b)
#define forever while(1)
#define pop() Q.front(); Q.pop()
const int NMAX = 1000;
const int MMAX = 5000;
const char IN[] = "maxflow.in", OUT[] = "maxflow.out";
using namespace std;
int N, M;
int G[NMAX][NMAX];
int Gf[NMAX][NMAX];
const int INF = 0x3f3f3f3f;
const int source = 1;
int drain;
inline void read_data()
{
assert(freopen(IN, "r", stdin));
assert(scanf("%d %d", &N, &M));
drain = N;
for (int i = 0; i < M; ++i) {
int u, v, c;
assert(scanf("%d %d %d", &u, &v, &c));
G[u][v] = c;
Gf[u][v] = c;
}
fclose(stdin);
}
int PI[NMAX];
bool inQ[NMAX];
list<int> path;
bool find_augmenting_paths()
{
queue<int> Q;
memset(inQ, 0, sizeof(inQ));
memset(PI, 0, sizeof(PI));
Q.push(source);
inQ[source] = true;
while (!Q.empty()) {
int u = pop();
for (int v = 1; v <= N; ++v) {
if (Gf[u][v] && !inQ[v]) {
PI[v] = u;
Q.push(v);
inQ[v] = true;
}
}
}
return inQ[N];
}
int maxflow()
{
int mflow = 0;
while (find_augmenting_paths()) {
for (int u = 1; u < N; ++u) {
if (inQ[u] && Gf[u][N]) {
int path_flow = Gf[u][N];
for (int node = u; node != source; node = PI[node]) {
path_flow = min(path_flow, Gf[PI[node]][node]);
}
if (path_flow == 0) continue;
Gf[u][N] -= path_flow;
for (int node = u; node != source; node = PI[node]) {
Gf[PI[node]][node] -= path_flow;
Gf[node][PI[node]] += path_flow;
}
mflow += path_flow;
}
}
}
return mflow;
}
int main()
{
read_data();
fprintf(fopen(OUT, "w"), "%d\n", maxflow());
return 0;
}