Cod sursa(job #1754978)

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

using ull = unsigned long long;
constexpr int maxn = 400;

constexpr int inf = 0x3f3f3f3f;

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

priority_queue<ull, vector<ull>, greater<ull>> pq;
int rez = 0;
vector<short> vec[maxn];

static inline bool bellman_ford(){
	memset(old_dist, 0x3f, sizeof(old_dist));
	old_dist[s] = 0;

	queue<short> 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; }

constexpr ull mp(const int x, const short y){
	return (x<<16) | y; }

static inline bool dijkstra_and_flux_step(){
	pq.push(mp(0, s));
	memset(dist, 0x3f, sizeof(dist));
	dist[s] = 0;

	while(!pq.empty()){
		const int cur = (pq.top()&(0xffff)), d_cur = (pq.top()>>16);
		pq.pop();
		if(dist[cur] != d_cur || cur == t){
			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;
				pq.push(mp(dist[next], next)); } } }

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

	memcpy(old_dist, dist, sizeof(dist));

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

	rez += total_cost * d_flux;
	for(int nod = t, f_nod; nod != s && (f_nod = father[nod]); nod = f_nod){
		flux_left[f_nod][nod] -= d_flux;
		flux_left[nod][f_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; }