Cod sursa(job #1133423)

Utilizator antonioteoZait Teodor Antonio antonioteo Data 4 martie 2014 21:07:52
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <algorithm>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

#define NMAX 1001
#define INF 0x3f3f3f3f

int i, j, N, M;
int A, B, n, c;
int x, minC;
int S, D;

bool used[NMAX];
int Father[NMAX];
queue <int> Q;

struct nod {
	int U;
	nod *next;
};
nod *v[NMAX];

void add(int A, int B) {
	nod *P = new nod;
	P->U = B;
	P->next = v[A];
	v[A] = P;
}

int Capacity[NMAX][NMAX];

int MinCapacity() {
	memset(used, 0, sizeof(used));
	memset(Father, 0, sizeof(Father));
	minC = INF;
	Q.push(S);
	used[S] = true;
	while (!Q.empty()) {
		x = Q.front();
		for (nod *it = v[x]; it; it = it->next) {
			if (!used[it->U] && Capacity[x][it->U] > 0) {
				used[it->U] = true;
				Father[it->U] = x;
				Q.push(it->U);
			}
		}
		Q.pop();
	}
	if (used[D] == false) 
		return INF;
	x = D;
	while (Father[x]) {
		minC = min(minC, Capacity[Father[x]][x]);
		x = Father[x];
	}
	if (minC <= 0) 
		return INF;
	x = D;
	while (Father[x]) {
		Capacity[Father[x]][x] -= minC;
		Capacity[x][Father[x]] += minC;
		x = Father[x];
	}
	return minC;
}

int cnt, MaxFlow;

int main() {
	fin >> N >> M;
	for (i = 1; i <= M; ++i) {
		fin >> A >> B >> c;
		Capacity[A][B] = c;
		add(A, B);
		add(B, A);
	}
	S = 1; 
	D = N;
	while (1) {
		cnt = MinCapacity();
		if (cnt == INF)
			break;
		MaxFlow += cnt;
	}
	fout << MaxFlow << '\n';
	return 0;
}