Cod sursa(job #1462677)

Utilizator GilgodRobert B Gilgod Data 18 iulie 2015 18:00:12
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#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;
list<int> G[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].push_back(v);
		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 (const int v: G[u]) {
			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;
}