Cod sursa(job #3132558)

Utilizator siliviuSilion Liviu siliviu Data 23 mai 2023 03:50:55
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;
using pi = pair<int, int>;

vector<int> G[351];
int s, t, cost[351][351], c[351][351], dd[351], inq[351], last[351], dp[351], dp2[351];

bool dijkstra() {
	priority_queue<pi, vector<pi>, greater<pi>> PQ;
	memset(dp, 0x3F, sizeof(dp));
	PQ.emplace(0, s);
	dp[s] = 0;
	while (!PQ.empty()) {
		int node, curcost;
		tie(curcost, node) = PQ.top();
		PQ.pop();
		if (dp[node] == curcost)
			for (auto x : G[node]) {
				int fakecost = cost[node][x] + dd[node] - dd[x];
				if (c[node][x] && curcost + fakecost < dp[x]) {
					last[x] = node;
					dp[x] = curcost + fakecost;
					dp2[x] = dp2[node] + cost[node][x];
					PQ.emplace(curcost + fakecost, x);
				}
			}
	}
	return dp[t] != 0x3F3F3F3F;
}

void spfa() {
	queue<int> Q;
	inq[s] = 1;
	memset(dd, 0x3F, sizeof(dd));
	dd[s] = 0;
	Q.emplace(s);
	while (!Q.empty()) {
		int node = Q.front();
		Q.pop();
		inq[node] = 0;
		for (auto x : G[node])
			if (c[node][x] && dd[node] + cost[node][x] < dd[x]) {
				dd[x] = dd[node] + cost[node][x];
				if (!inq[x]) {
					inq[x] = 1;
					Q.emplace(x);
				}
			}
	}
}

int main() {
	ifstream cin("fmcm.in");
	ofstream cout("fmcm.out");
	int n, m, x, y, z, w;
	cin >> n >> m >> s >> t;
	while (m--) {
		cin >> x >> y >> z >> w;
		G[x].emplace_back(y);
		G[y].emplace_back(x);
		cost[x][y] = w, cost[y][x] = -w;
		c[x][y] = z;
	}
	int flow = 0, curcost = 0;
	spfa();
	while (dijkstra()) {
		int curflow = INT_MAX;
		for (int i = t; i != s; i = last[i])
			curflow = min(curflow, c[last[i]][i]);
		for (int i = t; i != s; i = last[i]) {
			c[last[i]][i] -= curflow;
			c[i][last[i]] += curflow;
		}
		curcost += dp2[t] * curflow;
		flow += curflow;
		memcpy(dd, dp2, sizeof(dp2));
	}
	cout << curcost << '\n';
}