Cod sursa(job #1399399)

Utilizator vladrochianVlad Rochian vladrochian Data 24 martie 2015 18:48:48
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

const int kMaxN = 355;
const int kInf = 0x3f3f3f3f;

int N, M, S, D;
vector<pair<int, int>> G[kMaxN];
int cap[kMaxN][kMaxN];
int cost;

int dist[kMaxN], padre[kMaxN];
queue<int> q;
bool in_q[kMaxN];

void Read() {
	ifstream fin("fmcm.in");
	fin >> N >> M >> S >> D;
	while (M--) {
		int x, y, c, z;
		fin >> x >> y >> c >> z;
		G[x].emplace_back(y, z);
		G[y].emplace_back(x, -z);
		cap[x][y] = c;
	}
}

bool BellmanFord() {
	memset(dist, kInf, sizeof dist);
	dist[S] = 0;
	q.push(S);
	in_q[S] = true;
	while (!q.empty()) {
		int node = q.front();
		q.pop();
		in_q[node] = false;
		for (auto it : G[node])
			if (cap[node][it.first] && dist[node] + it.second < dist[it.first]) {
				dist[it.first] = dist[node] + it.second;
				padre[it.first] = node;
				if (!in_q[it.first]) {
					q.push(it.first);
					in_q[it.first] = true;
				}
			}
	}
	return dist[D] < kInf;
}

void Solve() {
	while (BellmanFord()) {
		int flow = kInf;
		for (int i = D; i != S; i = padre[i])
			flow = min(flow, cap[padre[i]][i]);
		for (int i = D; i != S; i = padre[i]) {
			cap[padre[i]][i] -= flow;
			cap[i][padre[i]] += flow;
		}
		cost += flow * dist[D];
	}
}

int main() {
	Read();
	Solve();
	ofstream("fmcm.out") << cost << "\n";
	return 0;
}