Pagini recente » Cod sursa (job #2711055) | Cod sursa (job #301728) | Cod sursa (job #1896150) | Cod sursa (job #2717975) | Cod sursa (job #2778961)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 350 + 7;
const int INF = (int) 1e9;
int n, m, s, d, cap[N][N], cost[N][N], minDist[N], minCap[N], par[N];
vector<int> g[N];
bool inq[N];
int main() {
//freopen ("input", "r", stdin);
freopen ("fmcm.in", "r", stdin), freopen ("fmcm.out", "w", stdout);
cin >> n >> m >> s >> d;
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
cin >> cap[x][y] >> cost[x][y];
cost[y][x] = -cost[x][y];
g[x].push_back(y);
g[y].push_back(x);
}
int maxflow = 0;
ll mincost = 0;
while (1) {
for (int i = 1; i <= n; i++) {
minDist[i] = INF;
}
minCap[s] = INF;
minDist[s] = 0;
queue<int> q;
q.push(s);
inq[s] = 1;
while (!q.empty()) {
int a = q.front();
inq[a] = 0;
q.pop();
for (auto &b : g[a]) {
if (!cap[a][b]) continue;
int upd = minDist[a] + cost[a][b];
if (upd < minDist[b]) {
minDist[b] = upd;
minCap[b] = min(minCap[a], cap[a][b]);
par[b] = a;
if (!inq[b]) {
q.push(b);
inq[b] = 1;
}
}
}
}
if (minDist[d] == INF) {
break;
}
maxflow += minCap[d];
mincost += (ll) minDist[d] * minCap[d];
vector<int> path;
{
int vertex = d;
while (vertex != s) {
path.push_back(vertex);
vertex = par[vertex];
}
path.push_back(s);
reverse(path.begin(), path.end());
}
for (int i = 0; i + 1 < (int) path.size(); i++) {
int x = path[i], y = path[i + 1];
cap[x][y] -= minCap[d];
cap[y][x] += minCap[d];
}
}
// cout << maxflow << "\n";
cout << mincost << "\n";
return 0;
}