Pagini recente » Cod sursa (job #3239346) | Cod sursa (job #3290234) | Cod sursa (job #1058317) | Cod sursa (job #2734818) | Cod sursa (job #726704)
Cod sursa(job #726704)
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
const int N = 353;
int n, s, d;
int best[N];
int viz[N];
int fat[N];
int f[N][N];
int c[N][N];
int cost[N][N];
void read() {
int m;
in >> n >> m >> s >> d;
while (m--) {
int a, b, cap, cst;
in >> a >> b >> cap >> cst;
c[a][b] = cap;
cost[a][b] = cst;
cost[b][a] = -cst;
}
}
bool road() {
queue <int> q;
memset(best, 0x3f3f3f3f, sizeof(best));
memset(viz, 0, sizeof(viz));
q.push(s);
best[s] = 0;
viz[s] = 1;
while (!q.empty()) {
int node = q.front();
for (int next = 1; next <= n; ++next)
if (c[node][next] - f[node][next] > 0 && best[node] + cost[node][next] < best[next]) {
++viz[next];
if (viz[next] == n)
return viz[d];
fat[next] = node;
best[next] = best[node] + cost[node][next];
q.push(next);
}
q.pop();
}
return viz[d];
}
long long solve() {
long long res = 0;
while (road()) {
int node = d;
int minFlow = 0x3f3f3f3f;
while (node != s) {
if (c[fat[node]][node] - f[fat[node]][node] < minFlow)
minFlow = c[fat[node]][node] - f[fat[node]][node];
node = fat[node];
}
node = d;
while (node != s) {
f[fat[node]][node] += minFlow;
f[node][fat[node]] -= minFlow;
res += minFlow * cost[fat[node]][node];
node = fat[node];
}
}
return res;
}
int main() {
read();
out << solve() << "\n";
return 0;
}