Pagini recente » Cod sursa (job #2281985) | Cod sursa (job #2291619) | Cod sursa (job #2606532) | Cod sursa (job #1149406) | Cod sursa (job #2955059)
#include <bits/stdc++.h>
using namespace std;
const int nmax = 357;
const int inf = 0x3f3f3f3f;
typedef long long llong;
int n, m, src, dst;
vector<int> adj[nmax];
int cap[nmax][nmax];
int cost[nmax][nmax];
int dist[nmax];
int fdist[nmax];
int cdist[nmax];
int par[nmax];
void bellmanFord() {
memset(fdist, inf, sizeof(fdist));
static bool inq[nmax];
inq[dst] = true;
queue<int> q;
q.push(src);
fdist[src] = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
inq[u] = false;
for (int v : adj[u]) {
if (cap[u][v] > 0 && fdist[u] + cost[u][v] < fdist[v]) {
fdist[v] = fdist[u] + cost[u][v];
if (!inq[v]) q.push(v), inq[v] = true;
}
}
}
}
void dijkstra() {
memset(dist, inf, sizeof(dist));
memset(par, -1, sizeof(par));
struct Comp {
bool operator()(const pair<int, int>& a, const pair<int, int>& b) const {
return a.second > b.second;
}
};
priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> pq;
pq.push({src, 0});
cdist[src] = 0;
dist[src] = 0;
par[src] = 0;
while (!pq.empty()) {
auto [u, d] = pq.top(); pq.pop();
if (dist[u] < d) continue;
for (int v : adj[u]) {
if (cap[u][v] > 0 && dist[u] + cost[u][v] + fdist[u] - fdist[v] < dist[v]) {
par[v] = u;
cdist[v] = cdist[u] + cost[u][v];
dist[v] = dist[u] + cost[u][v] + fdist[u] - fdist[v];
pq.push({v, dist[v]});
}
}
}
memcpy(fdist, cdist, sizeof(fdist));
}
llong solve() {
cin >> n >> m >> src >> dst;
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);
cap[u][v] = f;
cost[u][v] = c;
cost[v][u] = -c;
}
llong totalCost = 0;
bellmanFord();
for (;;) {
dijkstra();
if (par[dst] == -1) return totalCost;
int currentFlow = INT_MAX;
for (int u = dst; u != src; u = par[u]) {
currentFlow = min(currentFlow, cap[par[u]][u]);
}
for (int u = dst; u != src; u = par[u]) {
cap[par[u]][u] -= currentFlow;
cap[u][par[u]] += currentFlow;
}
totalCost += (llong)currentFlow * cdist[dst];
}
}
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;
}