Pagini recente » Cod sursa (job #1132044) | Cod sursa (job #2672617) | Cod sursa (job #2856735) | Cod sursa (job #1189248) | Cod sursa (job #2959210)
#include <bits/stdc++.h>
using namespace std;
const int nmax = 357;
const int inf = 0x3f3f3f3f;
int n, m, s, d;
vector<int> adj[nmax];
int cost[nmax][nmax];
int cap[nmax][nmax];
int par[nmax];
int dist[nmax];
int cdist[nmax];
int fdist[nmax];
void bellmanFord() {
memset(fdist, inf, sizeof(fdist));
static bool inq[nmax];
queue<int> q;
q.push(s);
inq[s] = true;
fdist[s] = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
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() {
struct PQ {
int node, dist;
bool operator<(const PQ& p) const {
return dist > p.dist;
}
};
memset(par, -1, sizeof(par));
memset(cdist, inf, sizeof(cdist));
priority_queue<PQ> pq;
pq.push({s, 0});
dist[s] = 0;
cdist[s] = 0;
par[s] = 0;
while (!pq.empty()) {
auto [u, dd] = pq.top(); pq.pop();
if (dd > cdist[u]) continue;
for (int v : adj[u]) {
if (cap[u][v] > 0 && cdist[u] + (cost[u][v] + fdist[u] - fdist[v]) < cdist[v]) {
par[v] = u;
cdist[v] = cdist[u] + (cost[u][v] + fdist[u] - fdist[v]);
dist[v] = dist[u] + cost[u][v];
pq.push({v, cdist[v]});
}
}
}
memcpy(fdist, dist, sizeof(fdist));
}
long long solve() {
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);
cap[u][v] = f;
cost[u][v] = c;
cost[v][u] = -c;
}
bellmanFord();
long long totalCost = 0;
for (;;) {
dijkstra();
if (par[d] == -1) return totalCost;
int currentFlow = INT_MAX;
for (int u = d; u != s; u = par[u]) {
currentFlow = min(currentFlow, cap[par[u]][u]);
}
for (int u = d; u != s; u = par[u]) {
cap[par[u]][u] -= currentFlow;
cap[u][par[u]] += currentFlow;
}
totalCost += (long long)currentFlow * (long long)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;
}