Pagini recente » Cod sursa (job #2885251) | Cod sursa (job #1114815) | Cod sursa (job #302802) | Cod sursa (job #1279858) | Cod sursa (job #2728620)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
const int N = 355, INF = 1e9;
int n, m, source, sink;
int flowMax, costMin;
int t[N], flow[N][N], cap[N][N], cost[N][N];
vector<int> g[N], realDist, positiveDist, newRealDist;
vector<bool> vis;
void BellmanFord()
{
vector<bool> inCoada(n + 1, false);
realDist.assign(n + 1, INF);
queue<int> coada;
coada.push(source);
inCoada[source] = true;
realDist[source] = 0;
t[source] = 0;
while (!coada.empty())
{
int x = coada.front();
coada.pop();
inCoada[x] = false;
for (int y : g[x])
{
if (realDist[x] + cost[x][y] < realDist[y] && flow[x][y] != cap[x][y])
{
t[y] = x;
realDist[y] = realDist[x] + cost[x][y];
if (!inCoada[y])
{
coada.push(y);
inCoada[y] = true;
}
}
}
}
}
void Dijkstra()
{
positiveDist.assign(n + 1, INF);
newRealDist.assign(n + 1, INF);
vis.assign(n + 1, false);
priority_queue<pair<int, int>> heap;
heap.push({ 0, source });
positiveDist[source] = newRealDist[source] = 0;
while (!heap.empty())
{
int x = heap.top().second;
heap.pop();
if (vis[x])
continue;
vis[x] = true;
for (int y : g[x])
{
int positiveCostXY = realDist[x] + cost[x][y] - realDist[y];
if (!vis[y] && flow[x][y] != cap[x][y] && positiveDist[x] + positiveCostXY < positiveDist[y])
{
positiveDist[y] = positiveDist[x] + positiveCostXY;
heap.push({ -positiveDist[y], y });
newRealDist[y] = newRealDist[x] + cost[x][y];
t[y] = x;
}
}
}
realDist = newRealDist;
}
void maxFlowMinCost()
{
BellmanFord();
while (true)
{
Dijkstra();
if (positiveDist[sink] == INF)
break;
int flowMin = 1 << 30;
for (int node = sink; node != source; node = t[node])
flowMin = min(flowMin, cap[t[node]][node] - flow[t[node]][node]);
flowMax += flowMin;
costMin += realDist[sink] * flowMin;
for (int node = sink; node != source; node = t[node])
{
flow[t[node]][node] += flowMin;
flow[node][t[node]] -= flowMin;
}
}
}
int main()
{
fin >> n >> m >> source >> sink;
for (int i = 0; i < m; i++)
{
int x, y, c, price;
fin >> x >> y >> c >> price;
g[x].push_back(y);
g[y].push_back(x);
cap[x][y] = c;
cost[x][y] = price;
cost[y][x] = -price;
}
maxFlowMinCost();
fout << costMin;
return 0;
}