Pagini recente » Cod sursa (job #25559) | Cod sursa (job #1046198) | Cod sursa (job #2356377) | Cod sursa (job #365577) | Cod sursa (job #3253642)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>
using namespace std;
const int MAXN = 1001;
const int INF = INT_MAX;
int N, M, S, D;
int capacity[MAXN][MAXN];
int cost[MAXN][MAXN];
int flow[MAXN][MAXN];
vector<int> adj[MAXN];
bool spfa(int dist[], int parent[], int maxFlow[]) {
fill(dist, dist + N + 1, INF);
dist[S] = 0;
maxFlow[S] = INF;
queue<int> q;
q.push(S);
bool inQueue[MAXN] = { false };
inQueue[S] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
inQueue[u] = false;
for (int v : adj[u]) {
if (capacity[u][v] - flow[u][v] > 0 && dist[u] + cost[u][v] < dist[v]) {
dist[v] = dist[u] + cost[u][v];
parent[v] = u;
maxFlow[v] = min(maxFlow[u], capacity[u][v] - flow[u][v]);
if (!inQueue[v]) {
q.push(v);
inQueue[v] = true;
}
}
}
}
return dist[D] != INF;
}
int minCostMaxFlow() {
int totalFlow = 0;
int totalCost = 0;
int dist[MAXN];
int parent[MAXN];
int maxFlow[MAXN];
while (spfa(dist, parent, maxFlow)) {
int pathFlow = maxFlow[D];
totalFlow += pathFlow;
totalCost += pathFlow * dist[D];
int v = D;
while (v != S) {
int u = parent[v];
flow[u][v] += pathFlow;
flow[v][u] -= pathFlow;
v = u;
}
}
return totalCost;
}
int main() {
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
fin >> N >> M >> S >> D;
memset(capacity, 0, sizeof(capacity));
memset(cost, 0, sizeof(cost));
memset(flow, 0, sizeof(flow));
for (int i = 0; i < M; i++) {
int x, y, c, z;
fin >> x >> y >> c >> z;
capacity[x][y] = c;
cost[x][y] = z;
cost[y][x] = -z;
adj[x].push_back(y);
adj[y].push_back(x);
}
int minCost = minCostMaxFlow();
fout << minCost << endl;
return 0;
}