Cod sursa(job #237551)

Utilizator pauldbPaul-Dan Baltescu pauldb Data 30 decembrie 2008 00:37:21
Problema Flux maxim de cost minim Scor Ascuns
Compilator cpp Status done
Runda Marime 2.48 kb
#include <stdio.h>
#include <assert.h>
#include <vector>

using namespace std;

#define maxn 360
#define inf 2000000000
#define ll long long

int N, M, S, D;
int Drum, L, Sum;
vector <int> A[maxn];
int G[maxn], Dist[maxn], From[maxn], H[maxn], P[maxn];
int C[maxn][maxn], F[maxn][maxn], Cost[maxn][maxn];

void push(int x)
{
	int aux;

	while (x/2>1 && Dist[H[x]]<Dist[H[x/2]])
	{
		aux = H[x], H[x] = H[x/2], H[x/2] = aux;

		P[H[x]] = x;
		P[H[x/2]] = x/2;

		x /= 2;
	}
}

void pop(int x)
{
	int y = 0, aux;

	while (x != y)
	{
		y = x;
		if (y*2<=L && Dist[H[x]]>Dist[H[y*2]]) x = y*2;
		if (y*2+1 <= L && Dist[H[x]]>Dist[H[y*2+1]]) x = y*2+1;

		aux = H[x], H[x] = H[y], H[y] = aux;
		P[H[x]] = x;
		P[H[y]] = y;
	}
}

int Dijkstra()
{
	int i, j;

	for (i = 1; i <= N; i++)
	{
		Dist[i] = inf;
		H[i] = i;
		P[i] = i;
		From[i] = -1;
	}

	Dist[S] = 0;
	H[1] = S, H[S] = 1;
	P[1] = S, P[S] = 1;
	L = N;

	while (L>1 && Dist[H[1]] != inf)
	{
		for (i = 0; i < G[H[1]]; i++)
		{
			int v = A[H[1]][i];
			if (C[H[1]][v]-F[H[1]][v]>0 && Dist[H[1]]+Cost[H[1]][v]<Dist[v])
			{
				Dist[v] = Dist[H[1]] + Cost[H[1]][v];
				From[v] = H[1];
				push(P[v]);
			}
		}

		H[1] = H[L--];
		P[H[1]] = 1;
		if (L > 1) pop(1);
	}

	for (i = 1; i <= N; i++)
		for (j = 0; j<G[i]; j++)
			if (C[i][A[i][j]]-F[i][A[i][j]]>0)
			{
				Cost[i][A[i][j]] += Dist[i] - Dist[A[i][j]];
				Cost[A[i][j]][i] += Dist[A[i][j]] - Dist[i];
			}

	if (Dist[D] != inf) 
	{
		int Vmin = inf;
		Drum = 1;

		for (i = D; i != S; i = From[i]) Vmin = min(Vmin, C[From[i]][i] - F[From[i]][i]);

		for (i = D; i != S; i = From[i]) 
		{
			F[From[i]][i] += Vmin;
			F[i][From[i]] -= Vmin;
		}

		Sum += Dist[D];

		return Vmin * Sum;
	}

	return 0;
}

ll Flux()
{
	ll Rez = 0;
	Drum = 1;

	while (Drum)
	{
		Drum = 0;
		Rez += Dijkstra();
	}

	return Rez;
}

int main()
{
	freopen("fmcm.in", "r", stdin);
	freopen("fmcm.out", "w", stdout);

	int i, x, y, z, cap;

	scanf("%d %d %d %d ", &N, &M, &S, &D);

	assert(1<=N && N<=350);
	assert(1<=M && M<=12500);
	assert(1<=S && S<=N);
	assert(1<=D && D<=N);
	assert(S != D);

	for (i = 1; i <= M; i++)
	{
		scanf("%d %d %d %d ", &x, &y, &cap, &z);

		assert(1<=x && x<=N);
		assert(1<=y && y<=N);
		assert(1<=cap && cap<=10000);
		assert(1<=z && z<=100);
		assert(C[x][y]!=0 && C[y][x]!=0);
		assert(x != y);
		assert(y != S && x != D);

		A[x].push_back(y);
		A[y].push_back(x);

		C[x][y] = cap;
		Cost[x][y] = z;
		Cost[y][x] = -z;
	}

	for (i = 1; i <= N; i++) G[i] = A[i].size();

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

	return 0;
}