Cod sursa(job #540547)

Utilizator cosmyoPaunel Cosmin cosmyo Data 24 februarie 2011 00:54:21
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <cstdio>
#include <vector>
using namespace std;
const int N = 512;
const int INF = 0x3f3f3f3f;
int f[N][N], n, m, DIST[N], S, D, c[N][N], G[N], COST[N][N];
vector<int> a[N];
int cd[1000010];
int BELLMAN_FORD() {
	int i, j, t[N], v[N], cost, cap, k, x;
	for(i = 1; i <= n; ++i) {
		DIST[i] = INF;
		t[i] = 0;
		v[i] = 0;
	}
	v[S] = 1;
	DIST[S] = 0;
	cd[0] = 1; cd[1] = S;

	for(j = 1; j <= cd[0]; ++j) {
		k = cd[j];

		for(i = 0; i < G[k]; ++i) {
			x = a[k][i];
			if(f[k][x] < c[k][x] && DIST[k] + COST[k][x] < DIST[x]) {
				DIST[x] = DIST[k] + COST[k][x];
				t[x] = k;
				if(!v[x]) {
					cd[++cd[0]] = x;
					v[x] = 1;
				}
			}
		}
		v[k] = 0;
	}
	int r;
	if(DIST[D] != INF) {
		k = D;
		r = INF;
		while(k != S) {
			r = min(r, c[t[k]][k] - f[t[k]][k]);
			k = t[k];
		}
		
		k = D;

		while(k != S) {
			f[k][t[k]] -= r;
			f[t[k]][k] += r;
			k = t[k];
		}

		return r * DIST[D];
	}

	return 0;
}
int main() {
	freopen("fmcm.in", "r", stdin);
	freopen("fmcm.out", "w", stdout);
	int i, y, cost, x, cap;
	scanf("%d %d %d %d", &n, &m, &S, &D);
	for(i = 1; i <= m; ++i) {
		scanf("%d %d %d %d", &x, &y, &cap, &cost);
		a[x].push_back(y);
		c[x][y] = cap;
		COST[x][y] = cost;
		COST[y][x] = -cost;
		a[y].push_back(x);
	}
	for(i = 1; i <= n; ++i)
		G[i] = a[i].size();
	long long ct = 0;
	long long X = 1;
	while(X)  {
		X = BELLMAN_FORD();
		ct += X;
	}

	printf("%lld\n", ct);

	return 0;
}