Pagini recente » Cod sursa (job #2481399) | Cod sursa (job #2986055) | Cod sursa (job #1977061) | Cod sursa (job #1753028) | Cod sursa (job #1789725)
#include <stdio.h>
#include <vector>
#include <queue>
#define maxdim 353
using namespace std;
int n, m, source, dest;
int cp[maxdim][maxdim], f[maxdim][maxdim], dist[maxdim], inq[maxdim], T[maxdim];
vector<pair<int, int>> G[maxdim];
int bf() {
for (int i = 1; i <= n; ++i) {
T[i] = 0;
dist[i] = (1 << 29);
inq[i] = 0;
}
queue<int> q;
dist[source] = 0;
q.push(source);
inq[source] = 1;
while (!q.empty()) {
int nod = q.front(); q.pop();
inq[nod] = 0;
for (auto &p : G[nod]) {
int vecin = p.first, cost = p.second;
if (cp[nod][vecin] > f[nod][vecin] && dist[vecin] > dist[nod] + cost) {
dist[vecin] = dist[nod] + cost;
T[vecin] = nod;
if (!inq[vecin]) {
q.push(vecin);
inq[vecin] = 1;
}
}
}
}
return dist[dest] != (1 << 29);
}
int fmcm() {
int flow_cost = 0;
while (bf()) {
int nod = dest;
int crt_flow = (1 << 29);
while (T[nod]) {
crt_flow = min(crt_flow, cp[T[nod]][nod] - f[T[nod]][nod]);
nod = T[nod];
}
nod = dest;
while (T[nod]) {
f[T[nod]][nod] += crt_flow;
f[nod][T[nod]] -= crt_flow;
nod = T[nod];
}
flow_cost += crt_flow * dist[dest];
}
return flow_cost;
}
int main() {
freopen("fmcm.in", "r", stdin);
freopen("fmcm.out", "w", stdout);
scanf("%d %d %d %d", &n, &m, &source, &dest);
for (int i = 1; i <= m; ++i) {
int x, y, cap, cost; scanf("%d %d %d %d", &x, &y, &cap, &cost);
cp[x][y] = cap;
G[x].push_back(make_pair(y, cost));
G[y].push_back(make_pair(x, -cost));
}
printf("%d\n", fmcm());
return 0;
}