Pagini recente » Borderou de evaluare (job #1152922) | Borderou de evaluare (job #2094245) | Borderou de evaluare (job #792023) | Borderou de evaluare (job #2469560) | Cod sursa (job #2722623)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 1e9;
const int N = 355;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int n, m, source, sink, fMax, cMax;
int cap[N][N], flow[N][N], costMatrix[N][N];
vector<pair<int, int>> g[N];
vector<int> t, dist;
vector<bool> vis;
void BellmanFordCoada(int s)
{
dist.assign(n + 1, INF);
vector<bool> inCoada(n + 1, false);
t.assign(n + 1, 0);
dist[s] = 0;
queue<int> q;
q.push(s);
inCoada[s] = true;
while(!q.empty())
{
int x = q.front();
q.pop();
inCoada[x] = false;
for(auto neigh : g[x])
{
int y = neigh.first;
int cost = neigh.second;
if(flow[x][y] < cap[x][y] && dist[x] + cost < dist[y])
{
dist[y] = dist[x] + cost;
t[y] = x;
if(!inCoada[y])
{
q.push(y);
inCoada[y] = true;
}
}
}
}
}
void computeNonNegativeGraph()
{
BellmanFordCoada(source);
for(int i = 1; i <= n; i++)
{
for(auto& vec : g[i])
vec.second = vec.second + dist[i] - dist[vec.first];
}
}
void Dijkstra(int s)
{
dist.assign(n + 1, INF);
vis.assign(n + 1, false);
t.assign(n + 1, 0);
priority_queue<pair<int, int>> heap;
dist[s] = 0;
heap.push({0, s});
int costTotal = 0;
while(!heap.empty())
{
int nod = heap.top().second;
int cost = -heap.top().first;
heap.pop();
if(vis[nod])
continue;
vis[nod] = true;
for(auto &y : g[nod])
if(!vis[y.first] && flow[nod][y.first] != cap[nod][y.first] && cost + y.second < dist[y.first])
{
heap.push({-(cost + y.second), y.first});
dist[y.first] = cost + y.second;
t[y.first] = nod;
}
}
}
int maxFlowMinCost()
{
fMax = 0;
cMax = 0;
do
{
Dijkstra(source);
if(dist[sink] == INF)
break;
int fmin = 1 << 30;
int realDistance = 0;
for(int node = sink; node != source; node = t[node])
{
fmin = min(fmin, cap[t[node]][node] - flow[t[node]][node]);
realDistance += costMatrix[t[node]][node];
}
if(fmin == 0)
continue;
fMax += fmin;
cMax += realDistance * fmin;
for(int node = sink; node != source; node = t[node])
{
flow[t[node]][node] += fmin;
flow[node][t[node]] -= fmin;
}
} while(dist[sink] != INF);
return cMax;
}
int main()
{
fin >> n >> m >> source >> sink;
for(int i = 0; i < m; i++)
{
int x, y, c, cost;
fin >> x >> y >> c >> cost;
g[x].push_back({y, cost});
g[y].push_back({x, -cost});
cap[x][y] = c;
costMatrix[x][y] = cost;
costMatrix[y][x] = -cost;
}
computeNonNegativeGraph();
fout << maxFlowMinCost() << '\n';
return 0;
}