Pagini recente » Cod sursa (job #1812656) | Cod sursa (job #662668) | Cod sursa (job #2868142) | Cod sursa (job #2706729) | Cod sursa (job #2964632)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in ("fmcm.in");
ofstream out ("fmcm.out");
#define pii pair <int, int>
const int max_size = 351, INF = 2e9 + 1;
int cap[max_size][max_size], cost[max_size][max_size], d[max_size], pr[max_size], t[max_size], aux[max_size], n, s, p;
vector <int> mc[max_size];
queue <int> q;
priority_queue <pii, vector <pii>, greater <pii>> pq;
void bf ()
{
for (int i = 1; i <= n; i++)
{
aux[i] = INF;
}
aux[s] = 0;
q.push(s);
while (!q.empty())
{
int nod = q.front();
q.pop();
d[nod] = 0;
for (auto f : mc[nod])
{
if (aux[nod] + cost[nod][f] < aux[f] && cap[nod][f] > 0)
{
aux[f] = aux[nod] + cost[nod][f];
if (d[f] == 0)
{
d[f] = 1;
q.push(f);
}
}
}
}
}
bool djk ()
{
for (int i = 1; i <= n; i++)
{
d[i] = INF;
pr[i] = INF;
}
d[s] = 0;
pr[s] = 0;
pq.push({0, s});
while (!pq.empty())
{
int val = pq.top().first, nod = pq.top().second;
pq.pop();
if (val == d[nod])
{
for (auto f : mc[nod])
{
if (cap[nod][f] > 0 && d[nod] + cost[nod][f] + aux[nod] - aux[f] < d[f])
{
d[f] = d[nod] + cost[nod][f] + aux[nod] - aux[f];
pr[f] = pr[nod] + cost[nod][f];
t[f] = nod;
pq.push({d[f], f});
}
}
}
}
return (d[p] != INF);
}
int main ()
{
int m;
in >> n >> m >> s >> p;
while (m--)
{
int x, y, fl, price;
in >> x >> y >> fl >> price;
mc[x].push_back(y);
mc[y].push_back(x);
cap[x][y] = fl;
cost[x][y] = price;
cost[y][x] = -price;
}
bf();
int ans = 0, maxflow = 0;
while (djk())
{
int nod = p, flux = INF;
while (nod != s)
{
flux = min(flux, cap[t[nod]][nod]);
nod = t[nod];
}
maxflow += flux;
nod = p;
while (nod != s)
{
cap[t[nod]][nod] -= flux;
cap[nod][t[nod]] += flux;
nod = t[nod];
}
ans += flux * pr[p];
for (int i = 1; i <= n; i++)
{
aux[i] = d[i];
}
}
out << ans;
in.close();
out.close();
return 0;
}