Pagini recente » Cod sursa (job #1780663) | Cod sursa (job #211093) | Cod sursa (job #1917567) | Cod sursa (job #3276664) | Cod sursa (job #2850958)
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
const short int NMAX = 350, QSIZE = (1 << 9) - 1;
const int INF = 1e9;
short int flow[NMAX + 1][NMAX + 1], cap[NMAX + 1][NMAX + 1], cst[NMAX + 1][NMAX + 1];
short int father[NMAX + 1], q[1 << 9];
int minDist[NMAX + 1];
bool inQ[NMAX + 1];
vector<int> adj[NMAX + 1];
short int bellmanFord(int src, int sink);
int pushFlow(int sink);
int main() {
short int n, m, src, sink, i, nd1, nd2;
int minCst;
FILE *fin = fopen("fmcm.in", "r");
fscanf(fin, "%hd%hd%hd%hd", &n, &m, &src, &sink);
for (i = 0; i < m; i++) {
fscanf(fin, "%hd%hd", &nd1, &nd2);
fscanf(fin, "%hd%hd", &cap[nd1][nd2], &cst[nd1][nd2]);
cst[nd2][nd1] = -cst[nd1][nd2];
adj[nd1].push_back(nd2);
adj[nd2].push_back(nd1);
}
fclose(fin);
minCst = 0;
while (bellmanFord(src, sink))
minCst += pushFlow(sink);
FILE *fout = fopen("fmcm.out", "w");
fprintf(fout, "%d", minCst);
fclose(fout);
return 0;
}
short int bellmanFord(int src, int sink) {
for (int i = 1; i <= NMAX; i++)
minDist[i] = INF, father[i] = 0;
short int l = 0, r = 1;
q[0] = src;
inQ[src] = 1;
minDist[src] = 0;
while (l != r) {
int nd = q[l];
l = (l + 1) & QSIZE;
inQ[nd] = 0;
for (auto nxt: adj[nd]) {
if (flow[nd][nxt] != cap[nd][nxt] && minDist[nxt] > minDist[nd] + cst[nd][nxt]) {
minDist[nxt] = minDist[nd] + cst[nd][nxt];
father[nxt] = nd;
if (!inQ[nxt]) {
inQ[nxt] = 1;
q[r] = nxt;
r = (r + 1) & QSIZE;
}
}
}
}
return father[sink];
}
int pushFlow(int sink) {
short int nd = sink, minFlow = 10000;
while (father[nd]) {
minFlow = min(minFlow, (short int)(cap[father[nd]][nd] - flow[father[nd]][nd]));
nd = father[nd];
}
nd = sink;
int minCst = 0;
while (father[nd]) {
minCst += (int)cst[father[nd]][nd] * minFlow;
flow[father[nd]][nd] += minFlow;
flow[nd][father[nd]] -= minFlow;
nd = father[nd];
}
return minCst;
}