Pagini recente » Cod sursa (job #1983716) | Cod sursa (job #2954668)
#include <bits/stdc++.h>
using namespace std;
const int nmax = 357;
const int inf = 0x3f3f3f3f;
typedef long long llong;
int n, m, s, d;
vector<int> adj[nmax];
int flow[nmax][nmax];
int cost[nmax][nmax];
int dist[nmax];
int par[nmax];
void bellmanFord() {
memset(dist, inf, sizeof(dist));
memset(par, -1, sizeof(par));
dist[s] = 0;
queue<int> q;
static bool inq[nmax];
q.push(s);
inq[s] = true;
while (!q.empty()) {
int u = q.front(); q.pop();
inq[u] = false;
for (int v : adj[u]) {
if (flow[u][v] > 0 && dist[u] + cost[u][v] < dist[v]) {
par[v] = u;
dist[v] = dist[u] + cost[u][v];
if (!inq[v]) q.push(v), inq[v] = true;
}
}
}
}
llong solve() {
memset(cost, inf, sizeof(cost));
cin >> n >> m >> s >> d;
for (int i = 0; i < m; i++) {
int u, v, f, c;
cin >> u >> v >> f >> c;
adj[u].push_back(v);
adj[v].push_back(u);
flow[u][v] = f;
cost[u][v] = c;
cost[v][u] = -c;
}
llong totalCost = 0;
for (;;) {
bellmanFord();
if (dist[d] > inf / 2) return totalCost;
int currentFlow = INT_MAX;
for (int u = d; u != s; u = par[u]) {
currentFlow = min(currentFlow, flow[par[u]][u]);
}
for (int u = d; u != s; u = par[u]) {
flow[par[u]][u] -= currentFlow;
flow[u][par[u]] += currentFlow;
}
totalCost += llong(currentFlow) * llong(dist[d]);
}
}
int main() {
#ifdef LOCAL
freopen("file.in", "r", stdin);
#else
freopen("fmcm.in", "r", stdin);
freopen("fmcm.out", "w", stdout);
#endif
ios_base::sync_with_stdio(false), cin.tie(NULL);
cout << solve() << endl;
}