Pagini recente » Cod sursa (job #2313696) | Cod sursa (job #1778440) | Cod sursa (job #3164759) | Cod sursa (job #353837) | Cod sursa (job #2722020)
#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, cmin;
int cap[N][N], flow[N][N];
vector<pair<int, int>> g[N];
vector<int> t, dist;
void BellmanFordCoada(int s)
{
dist.assign(n + 1, INF);
vector<bool> inCoada(n + 1);
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;
}
}
}
}
}
int maxFlowMinCost()
{
fmax = 0;
cmin = 0;
do
{
BellmanFordCoada(source);
if(dist[sink] == INF)
break;
int fmin = 1 << 30;
for(int node = sink; node != source; node = t[node])
fmin = min(fmin, cap[t[node]][node] - flow[t[node]][node]);
if(fmin == 0)
continue;
fmax += fmin;
cmin += dist[sink] * 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 cmin;
}
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;
}
fout << maxFlowMinCost() << '\n';
return 0;
}