Cod sursa(job #703859)

Utilizator mottyMatei-Dan Epure motty Data 2 martie 2012 15:01:33
Problema Flux maxim de cost minim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <queue>

using namespace std;

ifstream in("fmcm.in");
ofstream out("fmcm.out");

const int N = 353;
const int oo = 0x3f3f3f3f;

int n, s, d;

int vis[N];
int fat[N];
int cost[N];

int f[N][N];
int c[N][N];
int p[N][N];

void Read()
{
	int m;
	in >> n >> m >> s >> d;

	while (m--) {
		int x, y, cc, z;
		in >> x >> y >> cc >> z;
		c[x][y] = cc;
		p[x][y] = z;
		p[y][x] = -z;
	}
}

queue <int> q;

bool Road()
{
	memset(vis, 0, sizeof(vis));
	memset(cost, oo, sizeof(cost));
	q.push(s);

	while(!q.empty()) {
		int node = q.front();

		for (int i = 1; i <= n; ++i)
			if (c[node][i] - f[node][i] > 0 && cost[i] > cost[node] + p[node][i]) {
				cost[i] = cost[node] + p[node][i];
				fat[i] = node;
				++vis[i];

				if (vis[i] == n)
					return vis[d];

				q.push(i);
			}

		q.pop();
	}

	return vis[d];
}

int Solve()
{
	int totalPrice = 0;

	while (Road())
	{
		int node = d;
		int flow = oo;

		while (node != s)
		{
			if (c[fat[node]][node] - f[fat[node]][node] < flow)
				flow = c[fat[node]][node] - f[fat[node]][node];

			node = fat[node];
		}

		node = d;

		while (node != s)
		{
			f[fat[node]][node] += flow;
			f[node][fat[node]] -= flow;

			totalPrice += flow * p[fat[node]][node];

			node = fat[node];
		}
	}

	return totalPrice;
}

int main()
{
	Read();
	out << Solve() << "\n";

	return 0;
}