Pagini recente » Cod sursa (job #1007783) | Cod sursa (job #918024) | Cod sursa (job #2848672) | Cod sursa (job #1502341) | Cod sursa (job #3179630)
#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 head[nmax][nmax];
int cost[nmax][nmax];
int cap[nmax][nmax];
int dist[nmax];
int fdist[nmax];
int cdist[nmax];
int par[nmax];
void bellmanFord() {
memset(fdist, inf, sizeof(fdist));
vector<bool> inq(nmax);
queue<int> q;
q.push(s);
fdist[s] = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
inq[u] = false;
for (int v : adj[u]) {
if (cap[u][v] > 0 && fdist[v] > fdist[u] + cost[u][v]) {
fdist[v] = fdist[u] + cost[u][v];
if (!inq[v]) q.push(v), inq[v] = true;
}
}
}
}
void dijkstra() {
struct Pos {
int node, dist;
bool operator<(const Pos& p) const {
return dist > p.dist;
}
};
memset(cdist, inf, sizeof(cdist));
memset(dist, inf, sizeof(dist));
memset(par, -1, sizeof(par));
priority_queue<Pos> pq;
pq.push({s, 0});
dist[s] = 0;
cdist[s] = 0;
while (!pq.empty()) {
auto [u, ds] = pq.top(); pq.pop();
if (dist[u] < ds) continue;
for (int v : adj[u]) {
if (cap[u][v] > 0 && dist[v] > dist[u] + fdist[u] - fdist[v] + cost[u][v]) {
dist[v] = dist[u] + fdist[u] - fdist[v] + cost[u][v];
cdist[v] = cdist[u] + cost[u][v];
par[v] = u;
pq.push({v, dist[v]});
}
}
}
memcpy(fdist, cdist, sizeof(fdist));
}
void 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;
head[u][v] = u;
head[v][u] = u;
}
bellmanFord();
typedef long long llong;
for (;;) {
dijkstra();
if (par[d] == -1) break;
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;
}
}
long long totalCost = 0;
for (int u = 1; u <= n; u++) {
for (int v = u + 1; v <= n; v++) {
if (head[u][v] == 0) continue;
totalCost += 1ll * cap[u+v-head[u][v]][head[u][v]] * cost[head[u][v]][u+v-head[u][v]];
}
}
cout << totalCost << endl;
}
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);
solve();
}