Cod sursa(job #2889046)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 12 aprilie 2022 09:22:03
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>

using namespace std;

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

const int INF = 1e9;

int n, m, ans, cost, s, d;
vector<bool> inQ;
vector<int> dist, parent, freq;
vector<vector<pair<int, int>>> edges;
vector<vector<int>> capacity, flow;

bool bf(int s, int d) {
	parent = vector<int> (n + 1, -1);
	inQ = vector<bool> (n + 1, 0);
	dist = vector<int> (n + 1, INF);
	freq = vector<int> (n + 1, 0);
	queue<int> q;

	q.push(s);
	inQ[s] = 1;
	dist[s] = 0;

	while(!q.empty()) {
		int node = q.front();
		q.pop();
		inQ[node] = 0;

		for(auto it: edges[node]) {
			if(flow[node][it.first] == capacity[node][it.first]) {
				continue;
			}

			if(dist[it.first] > dist[node] + it.second) {
				dist[it.first] = dist[node] + it.second;
				parent[it.first] = node;

				if(!inQ[it.first]) {
					q.push(it.first);
					inQ[it.first] = 1;
				}

				if(++freq[it.first] >= n) {
					return 0;
				}
			}
		}
	}

	return dist[d] != INF;
}

int main() {
	fin >> n >> m >> s >> d;

	edges = vector<vector<pair<int, int>>> (n + 1);
	capacity = vector<vector<int>>(n + 1, vector<int> (n + 1, 0));
	flow = vector<vector<int>>(n + 1, vector<int> (n + 1, 0));

	for(int i = 1; i <= m; i++) {
		int x, y, c, z;
		fin >> x >> y >> c >> z;

		capacity[x][y] = c;
		edges[x].push_back({y, z});
		edges[y].push_back({x, -z});
	}

	while(bf(s, d)) {
		int maxflow = INF;

		for(int p = d; p != s; p = parent[p]) {
			maxflow = min(maxflow, capacity[parent[p]][p] - flow[parent[p]][p]);
		}

		if(maxflow == 0) {
			continue;
		}

		for(int p = d; p != s; p = parent[p]) {
			flow[p][parent[p]] -= maxflow;
			flow[parent[p]][p] += maxflow;
		}

		// cout << maxflow << " " << dist[d] << " => ";
		// for(int p = d; p != s; p = parent[p]) {
		// 	cout << p << " ";
		// }
		// cout << '\n';

		ans += maxflow;
		cost += maxflow * dist[d];
	}

	fout << /*ans << " " <<*/ cost << '\n';
	return 0;
}