Cod sursa(job #1754976)

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

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<pair<int, short>, vector<pair<int, short>>, greater<pair<int, short>>> pq;
int rez = 0;
vector<short> vec[maxn];

template <typename T, int maxsz>
class static_queue{
	T buf[maxsz], *l = buf, *r = buf;
public:
	static_queue(){}
	void push(const T x){
		*r++ = x;
		if(r == buf+maxsz){
			r = buf; } }
	T front(){
		return *l; }
	bool empty(){
		return l == r; }
	void pop(){
		++l;
		if(l == buf+maxsz){
			l = buf; } } };

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

	static_queue<short, maxn> 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; }

bool dijkstra_and_flux_step(){
	pq.emplace(0, s);
	memset(dist, 0x3f, sizeof(dist));
	dist[s] = 0;

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

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

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

	register int d_flux = inf, total_cost = 0;
	for(register 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(register 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(){
	ifstream f("fmcm.in");
	ofstream g("fmcm.out");

	f >> n >> m >> s >> t;
	for(int i = 0, x, y, c, l; i < m; ++i){
		f >> x >> y >> c >> l;
		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());

	g << rez << endl;

	return 0; }