Pagini recente » Cod sursa (job #362792) | Cod sursa (job #428877) | Cod sursa (job #279739) | Cod sursa (job #2668848) | Cod sursa (job #1413941)
#include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
const int N = 355, inf = (1ll << 31) - 1;
vector <int> graph [N];
int f [N][N], c [N][N], cost [N][N], l [N], father [N];
bool in_q [N];
int n;
bool bellmanford (int s, int d) {
int i;
queue <int> q;
vector <int> :: iterator it;
for (i = 1; i <= n; i ++)
l [i] = inf;
memset (in_q, 0, sizeof (in_q));
q.push (s);
in_q [s] = 1;
l [s] = 0;
while (!q.empty ()) {
i = q.front ();
q.pop ();
for (it = graph [i].begin (); it != graph [i].end (); ++ it)
if (c [i][*it] - f [i][*it] > 0)
if (l [*it] > l [i] + cost [i][*it]) {
l [*it] = l [i] + cost [i][*it];
father [*it] = i;
if (in_q [*it] == 0) {
q.push (*it);
in_q [*it] = 1;
}
}
in_q [i] = 0;
}
if (l [d] != inf)
return 1;
return 0;
}
int main () {
int i, x, y, cap, z, s, d, ans = 0, m, minflow;
freopen ("fmcm.in", "r", stdin);
freopen ("fmcm.out", "w", stdout);
scanf ("%d%d%d%d", &n, &m, &s, &d);
for (i = 1; i <= m; i ++) {
scanf ("%d%d%d%d", &x, &y, &cap, &z);
c [x][y] = cap;
cost [x][y] = z;
cost [y][x] = -z;
graph [x].push_back (y);
graph [y].push_back (x);
}
while (bellmanford (s, d)) {
minflow = inf;
for (i = d; i != s; i = father [i])
minflow = min (minflow, c [father [i]][i] - f [father [i]][i]);
if (minflow == 0)
continue;
for (i = d; i != s; i = father [i]) {
f [father [i]][i] += minflow;
f [i][father [i]] -= minflow;
ans = ans + minflow * cost [father [i]][i];
}
}
printf ("%d\n", ans);
return 0;
}