Pagini recente » Profil balint1529 | Diferente pentru olimpici intre reviziile 180 si 63 | Cod sursa (job #179145) | Cod sursa (job #1972667) | Cod sursa (job #2531327)
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string.h>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
#ifdef DEBUG
string name = "data";
#else
string name = "fmcm";
#endif
ifstream fin(name + ".in");
ofstream fout(name + ".out");
#define MAXN 351
int n, m, s, t;
int c[MAXN][MAXN];
int f[MAXN][MAXN];
int d[MAXN][MAXN];
vector<int> g[MAXN];
int parent[MAXN];
bool inQueue[MAXN];
int dist[MAXN];
bool bellmanFord() {
memset(inQueue, false, sizeof(inQueue));
memset(dist, 0x3f, sizeof(dist));
queue<int> q;
q.push(s);
inQueue[s] = true;
dist[s] = 0;
bool reachedSink = false;
while (!q.empty()) {
auto node = q.front();
q.pop();
inQueue[node] = false;
for (auto x: g[node]) {
bool allowsFlow = f[node][x] != c[node][x];
if (allowsFlow && (dist[x] > dist[node] + d[node][x])) {
dist[x] = dist[node] + d[node][x];
parent[x] = node;
if (!inQueue[node]) {
q.push(x);
inQueue[x] = true;
}
if (x == t) {
reachedSink = true;
}
}
}
}
return reachedSink;
}
int main() {
fin >> n >> m >> s >> t;
for (int i = 0; i < m ; ++i) {
int x, y, cc, dd;
fin >> x >> y >> cc >> dd;
c[x][y] = cc;
d[x][y] = dd;
d[y][x] = -dd;
g[x].push_back(y);
g[y].push_back(x);
}
int flow = 0;
int cost = 0;
while (bellmanFord()) {
int minFlow = INF;
int node = t;
while (node != s) {
int p = parent[node];
minFlow = min(minFlow, c[p][node] - f[p][node]);
node = p;
}
node = t;
while (node != s) {
int p = parent[node];
cost += minFlow * d[p][node];
f[p][node] += minFlow;
f[node][p] -= minFlow;
node = p;
}
flow += minFlow;
}
fout << cost;
return 0;
}