Cod sursa(job #2689607)

Utilizator Constantin.Dragancea Constantin Constantin. Data 21 decembrie 2020 15:47:56
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.61 kb
#include <bits/stdc++.h>
using namespace std;
 
const int N = 400;
int n, m, s, d;
vector <int> graph[N];
int cap[N][N], cost[N][N];
queue <int> Q;
priority_queue < pair <int, int> > S;
int old_dist[N], dist[N], pr[N];
bool vis[N];

class InParser{
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch(){
		++sp;
		if (sp == 4096){
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume){
		fin = fopen(nume, "r");
		buff = new char[4096];
		sp = 4095;
	}

	InParser& operator>> (int &n){
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-'){
			n = 0;
			sgn = -1;
		}
		else{
			n = c - '0';
		}
		while(isdigit(c = read_ch())){
			n = n * 10 + c - '0';
		}
		n *= sgn;

		return *this;
	}
};
 
inline void Bellman(){
	for (int i = 1; i <= n; ++i){
		old_dist[i] = 1e9;
		vis[i] = 0;
	}
	
	Q.push(s);
	old_dist[s] = 0;
	vis[s] = 1;

	int node, curr_cost, new_dist;
	
	while (not Q.empty()){
		node = Q.front();
		curr_cost = old_dist[node];
		Q.pop();
		vis[node] = 0;
		
		for (int nei: graph[node]){
			if (!cap[node][nei])
				continue;
			new_dist = curr_cost + cost[node][nei];
			if (new_dist < old_dist[nei]){
				old_dist[nei] = new_dist;
				if (!vis[nei]){
					Q.push(nei);
					vis[nei] = 1;
				}
			}
		}
	}
}
 
inline int Dijkstra(){
	for (int i = 1; i <= n; ++i)
		dist[i] = 1e9;
	
	S.push({0, s});
	dist[s] = 0;

	int curr_cost, node, new_dist;
	
	while (not S.empty()){
		curr_cost = -S.top().first;
		node = S.top().second;
		S.pop();
		
		if (curr_cost != dist[node])
			continue;
		
		for (int nei: graph[node]){
			if (!cap[node][nei])
				continue;
			new_dist = curr_cost + cost[node][nei] + old_dist[node] - old_dist[nei];
			if (new_dist < dist[nei]){
				dist[nei] = new_dist;
				S.push({-dist[nei], nei});
				pr[nei] = node;
			}
		}
	}
	
	if (dist[d] == 1e9)
		return 0;
	
	int flow = 1e9, path_cost = 0;
	for (int node = d; node != s; node = pr[node])
		flow = min(flow, cap[pr[node]][node]);
	
	for (int node = d; node != s; node = pr[node]){
		cap[pr[node]][node] -= flow;
		cap[node][pr[node]] += flow;
		path_cost += cost[pr[node]][node];
	}
	
	for (int i = 1; i <= n; ++i)
		old_dist[i] = dist[i];
	
	return path_cost * flow;
}
 
int main(){
	InParser fin("fmcm.in");
	ofstream fout("fmcm.out");
	
	fin >> n >> m >> s >> d;
	while (m--){
		int a, b, c, z;
		fin >> a >> b >> c >> z;
		graph[a].push_back(b);
		graph[b].push_back(a);
		cap[a][b] = c;
		cost[a][b] = z;
		cost[b][a] = -z;
	}
	
	Bellman();
	int ans = 0, path_cost = 0;
	do{
		path_cost = Dijkstra();
		ans += path_cost;
	} while(path_cost);
	
	fout << ans << '\n';
	
	return 0;
}