Cod sursa(job #1755165)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 9 septembrie 2016 15:14:14
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include <bits/stdc++.h>
using namespace std;

constexpr int maxn = 352;

constexpr int inf = 0x3f3f3f3f;

int n, m, s, t, dist[maxn] = {}, old_dist[maxn] = {}, father[maxn] = {},
	len[maxn][maxn] = {}, flux_left[maxn][maxn] = {};

priority_queue<pair<int, int>> pq;
int rez = 0;
vector<int> vec[maxn];

static inline bool bellman_ford(){
	memset(old_dist, 0x3f, (n+1) * sizeof(int));
	old_dist[s] = 0;

	queue<int> q;
	bitset<maxn> in_q = 0;

	q.push(s), in_q[s] = true;
	while(!q.empty()){
		const int cur = q.front();
		q.pop(), in_q[cur] = false;
		for(const auto next : vec[cur]){
			if(flux_left[cur][next] && old_dist[cur] + len[cur][next] < old_dist[next]){
				old_dist[next] = old_dist[cur] + len[cur][next];
				if(!in_q[next]){
					in_q[next] = true;
					q.push(next); } } } }

	return dist[t] != inf; }

static inline bool dijkstra_and_flux_step(){
	pq.emplace(0, s);
	memset(dist, 0x3f, (n+1) * sizeof(int));
	dist[s] = 0;

	while(!pq.empty()){
		const int cur = pq.top().second, d_cur = -pq.top().first;
		pq.pop();
		if(dist[cur] != d_cur){
			continue; }
		for(const auto& next : vec[cur]){
			if(!flux_left[cur][next]) continue;
			const int new_dist = dist[cur] + len[cur][next] + old_dist[cur] - old_dist[next];
			if(new_dist < dist[next]){
				dist[next] = new_dist;
				father[next] = cur;
				if(next != t){
					pq.emplace(-dist[next], next); } } } }

	if(dist[t] == inf){
		return false; }

	memcpy(old_dist, dist, (n+1) * sizeof(int));

	int d_flux = inf, total_cost = 0;
	for(int nod = t;  nod != s; nod = father[nod]){
		d_flux = min<int>(d_flux, flux_left[father[nod]][nod]);
		total_cost += len[father[nod]][nod]; }

	rez += total_cost * d_flux;
	for(int nod = t; nod != s; nod = father[nod]){
		flux_left[father[nod]][nod] -= d_flux;
		flux_left[nod][father[nod]] += d_flux; }

	return true; }

int main(){
	FILE *f = fopen("fmcm.in", "r"),
		 *g = fopen("fmcm.out", "w");

	assert(fscanf(f, "%d %d %d %d", &n, &m, &s, &t) == 4);
	for(int i = 0, x, y, c, l; i < m; ++i){
		assert(fscanf(f, "%d %d %d %d", &x, &y, &c, &l) == 4);
		vec[x].push_back(y);
		vec[y].push_back(x);

		flux_left[x][y] = c;
		len[x][y] = l, len[y][x] = -l; }

	bellman_ford();
	while(dijkstra_and_flux_step());

	fprintf(g, "%d\n", rez);

	return 0; }