Cod sursa(job #2749907)

Utilizator vladvlad00Vlad Teodorescu vladvlad00 Data 8 mai 2021 22:21:35
Problema Flux maxim de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstring>

using namespace std;

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

constexpr int INF = 1e9;

int n, m, source, sink;
vector<pair<int,int>> L[355];
int cap[355][355], flux[355][355], cost[355][355];
int tata[355];

bool dijkstra()
{
	memset(tata, 0, sizeof(tata));
	vector<int> d(n+1, INF);
	d[source] = 0;
	priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
	pq.emplace(0, source);
	while (!pq.empty())
	{
		auto aux = pq.top(); pq.pop();
		if (aux.first > d[aux.second])
			continue;
		if (aux.second == sink)
			break;
		for (auto i : L[aux.second])
			if (flux[aux.second][i.first] < cap[aux.second][i.first] && d[i.first] > i.second + aux.first)
			{
				d[i.first] = i.second + aux.first;
				tata[i.first] = aux.second;
				pq.emplace(d[i.first], i.first);
			}
	}
	return d[sink] != INF;
}

int main()
{
    cin >> n >> m >> source >> sink;
	for (int i=1;i<=m;i++)
	{
		int x, y, z, c;
		cin >> x >> y >> z >> c;
		cap[x][y] += z;
		cost[x][y] += c;
		cost[y][x] -= c;
		L[x].emplace_back(y,c);
		L[y].emplace_back(x,-c);
	}
	int ans = 0;
	while (dijkstra())
	{
		int nod = sink;
		int minim = INF;
		while (nod != source)
		{
			minim = min(minim, cap[tata[nod]][nod] - flux[tata[nod]][nod]);
			nod = tata[nod];
		}
		nod = sink;
		while (nod != source)
		{
			flux[tata[nod]][nod] += minim;
			ans += minim * cost[tata[nod]][nod];
			nod = tata[nod];
		}
	}
	cout << ans << '\n';
    return 0;
}