Pagini recente » Cod sursa (job #99029) | Cod sursa (job #1460383) | Cod sursa (job #1653907) | Cod sursa (job #2983094) | Cod sursa (job #1956217)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <bitset>
#define MAXN 360
#define inf 0x3f3f3f3f
using namespace std;
int n, m, s, d;
int cost[MAXN][MAXN], capac[MAXN][MAXN], flux[MAXN][MAXN];
vector<int> graf[MAXN];
void citire()
{
scanf("%d %d %d %d", &n, &m, &s, &d);
for (int i = 1; i <= m; i++) {
int x, y, c, z;
scanf("%d %d %d %d", &x, &y, &c, &z);
capac[x][y] = c;
cost[x][y] = z;
cost[y][x] = -z;
graf[x].push_back(y);
graf[y].push_back(x);
}
}
queue<int> q;
bitset<MAXN> inq;
int best[MAXN];
void bellman()
{
for (int i = 0; i <= n; i++)
best[i] = inf;
q.push(s);
best[s] = 0;
while (!q.empty()) {
int top = q.front();
q.pop();
for (int y : graf[top]) {
if (capac[top][y] > flux[top][y] && best[top]+cost[top][y] < best[y]) {
best[y] = best[top] + cost[top][y];
if (!inq[y])
q.push(y);
}
}
}
}
int djmi[MAXN], parent[MAXN], real[MAXN];
struct cmp
{
bool operator()(const int &x, const int &y) const
{
return djmi[x] > djmi[y];
}
};
priority_queue<int, vector<int>, cmp> heap;
int dijkstra()
{
for (int i = 0; i <= n; i++)
djmi[i] = inf;
heap.push(s);
djmi[s] = 0;
while (!heap.empty()) {
int top = heap.top();
heap.pop();
for (int y : graf[top]) {
int nc = cost[top][y] + best[top] - best[y];
if (capac[top][y] > flux[top][y] && djmi[top]+nc < djmi[y]) {
djmi[y] = djmi[top] + nc;
real[y] = real[top] + cost[top][y];
parent[y] = top;
heap.push(y);
}
}
}
return (djmi[d] != inf);
}
int rez = 0;
void solve()
{
for (bellman(); dijkstra(); ) {
int mini = inf, cost = 0;
for (int y = d; y != s; y = parent[y])
mini = min(mini, capac[parent[y]][y] - flux[parent[y]][y]);
for (int y = d; y != s; y = parent[y]) {
flux[parent[y]][y] += mini;
flux[y][parent[y]] -= mini;
}
rez += mini*real[d];
for (int i = 1; i <= n; i++)
best[i] = real[i];
}
}
int main()
{
freopen("fmcm.in", "r", stdin);
freopen("fmcm.out", "w", stdout);
citire();
solve();
printf("%d", rez);
return 0;
}