Pagini recente » Cod sursa (job #1749929) | Monitorul de evaluare | Cod sursa (job #1517994) | Cod sursa (job #2074412) | Cod sursa (job #2875466)
#include <bits/stdc++.h>
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
// #define f cin
// #define g cout
const int nmax = 352;
vector<int> v[nmax];
int cap[nmax][nmax], we[nmax][nmax];
int n, m, source, sink, final_cost, potential[nmax], dp[nmax], realc[nmax], pre[nmax];
queue<int> q;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<bool> inq(nmax, false);
void bellman_ford();
bool dijkstra();
int32_t main()
{
f >> n >> m >> source >> sink;
for (int x, y; m; m--)
{
f >> x >> y >> cap[x][y] >> we[x][y];
v[x].push_back(y);
v[y].push_back(x);
we[y][x] = -we[x][y];
}
bellman_ford();
while (dijkstra())
;
g << final_cost;
return 0;
}
void bellman_ford()
{
memset(potential, 0x3f3f3f3f, sizeof potential);
q.push(source);
potential[source] = 0;
inq[source] = 1;
while (!q.empty())
{
static int ac, nc;
ac = q.front();
inq[ac] = 0;
q.pop();
for (const int &i : v[ac])
if (cap[ac][i])
{
nc = potential[ac] + we[ac][i];
if (nc < potential[i])
{
potential[i] = nc;
if (inq[i])
continue;
inq[i] = 1;
q.push(i);
}
}
}
}
bool dijkstra()
{
memset(dp, 0x3f3f3f3f, sizeof dp);
realc[source] = dp[source] = 0;
pq.push({0, source});
while (!pq.empty())
{
static int nod, cst, ne;
nod = pq.top().second;
cst = pq.top().first;
pq.pop();
if (cst != dp[nod])
continue;
for (const int &i : v[nod])
if (cap[nod][i])
{
ne = dp[nod] + we[nod][i] + potential[nod] - potential[i];
if (ne < dp[i])
{
dp[i] = ne;
realc[i] = realc[nod] + we[nod][i];
pre[i] = nod;
pq.push({ne, i});
}
}
}
memcpy(potential, realc, sizeof potential);
if (dp[sink] == (0x3f3f3f3f))
return 0;
int mnm = INT_MAX;
for (int ax = sink; ax != source; ax = pre[ax])
mnm = min(mnm, cap[pre[ax]][ax]);
final_cost += mnm * realc[sink];
for (int ax = sink; ax != source; ax = pre[ax])
{
cap[pre[ax]][ax] -= mnm;
cap[ax][pre[ax]] += mnm;
}
return 1;
}