Pagini recente » Cod sursa (job #199279) | Cod sursa (job #1865916) | Rating mates constantin (mates97) | Istoria paginii runda/08022000/clasament | Cod sursa (job #976638)
Cod sursa(job #976638)
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 400;
int f[NMAX][NMAX], cap[NMAX][NMAX], cost[NMAX][NMAX];
struct MaxFlowMinCost {
long long maxFlow, minCost;
int source, sink, N;
int dist[NMAX], father[NMAX];
vector <int> G[NMAX];
queue <int> Q;
bool inQ[NMAX];
void init(int S, int T, int n) {
maxFlow = minCost = 0;
source = S; sink = T; N = n;
}
void addEdge(int x0, int y0, int edgeCap, int edgeCost) {
cap[x0][y0] = edgeCap;
cost[x0][y0] = edgeCost;
cost[y0][x0] = -edgeCost;
G[x0].push_back(y0);
G[y0].push_back(x0);
}
void initBellmanFord() {
int i;
for (i = 0; i <= N; ++i)
dist[i] = 1 << 30;
dist[source] = 0; Q.push(source);
}
bool BellmanFord() {
initBellmanFord();
while (!Q.empty()) {
int nod = Q.front();
vector <int> :: iterator it;
for (it = G[nod].begin(); it != G[nod].end(); ++it)
if (f[nod][*it] < cap[nod][*it])
if (dist[*it] > dist[nod] + cost[nod][*it]) {
dist[*it] = dist[nod] + cost[nod][*it];
father[*it] = nod;
if (!inQ[*it]) {
inQ[*it] = true;
Q.push(*it);
}
}
Q.pop(); inQ[nod] = false;
}
return dist[sink] != 1 << 30;
}
void augment() {
int nod = sink, fmin = 1 << 30;
while (nod != source) {
if (fmin > cap[father[nod]][nod] - f[father[nod]][nod])
fmin = cap[father[nod]][nod] - f[father[nod]][nod];
nod = father[nod];
}
nod = sink;
while (nod != source) {
f[father[nod]][nod] += fmin;
f[nod][father[nod]] -= fmin;
nod = father[nod];
}
minCost += dist[sink] * fmin;
maxFlow += fmin;
}
void solve() {
while (BellmanFord())
augment();
}
};
int main() {
freopen("fmcm.in", "r", stdin);
freopen("fmcm.out", "w", stdout);
int i, N, M, S, D;
scanf("%d%d%d%d", &N, &M, &S, &D);
MaxFlowMinCost network;
network.init(S, D, N);
for (i = 1; i <= M; ++i) {
int x0, y0, curCap, curCost;
scanf("%d%d%d%d", &x0, &y0, &curCap, &curCost);
network.addEdge(x0, y0, curCap, curCost);
}
network.solve();
printf("%lld", network.minCost);
return 0;
}