Pagini recente » Cod sursa (job #1278284) | Cod sursa (job #463330) | Cod sursa (job #1742355) | Cod sursa (job #2277839) | Cod sursa (job #2427544)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <string.h>
#define inf 0x3f3f3f3f
#define nmax 350
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int minv(int x, int y)
{
return x < y ? x : y;
}
struct node
{
int x, c;
bool operator < (const node& other)const
{
return c > other.c;
}
};
int n, m, S, D, t[nmax + 5], cap[nmax + 5][nmax + 5], cost[nmax + 5][nmax + 5], dist[nmax + 5], d[nmax + 5], real_d[nmax + 5], flowmax;
vector<int> g[nmax + 5];
queue<int> qb;
bitset<nmax + 5> viz;
priority_queue<node> qd;
void Bellman_Ford()
{
int nod;
qb.push(S);
viz[S] = 1;
memset(dist, inf, sizeof(dist));
dist[S] = 0;
while (!qb.empty())
{
nod = qb.front();
qb.pop();
viz[nod] = 0;
for (int fiu : g[nod])
if (cap[nod][fiu])
if (dist[fiu] > dist[nod] + cost[nod][fiu])
{
dist[fiu] = dist[nod] + cost[nod][fiu];
if (!viz[fiu])
{
qb.push(fiu);
viz[fiu] = 1;
}
}
}
}
bool dijkstra()
{
int nod, cc;
memset(t, 0, sizeof(t));
memset(d, inf, sizeof(d));
d[S] = 0;
t[S] = S;
real_d[S] = 0;
qd.push({ S,0 });
while (!qd.empty())
{
nod = qd.top().x;
cc = qd.top().c;
qd.pop();
if (cc != d[nod])
continue;
for (int fiu : g[nod])
if (cap[nod][fiu])
{
int new_d = d[nod] + (cost[nod][fiu] + dist[nod] - dist[fiu]);
if (new_d < d[fiu])
{
d[fiu] = new_d;
real_d[fiu] = real_d[nod] + cost[nod][fiu];
t[fiu] = nod;
qd.push({ fiu,d[fiu] });
}
}
}
for (int i = 1; i <= n; i++)
dist[i] = real_d[i];
if (d[D] == inf)
return 0;
int flow = inf;
for (int i = D; i != S; i = t[i])
flow = minv(flow, cap[t[i]][i]);
for (int i = D; i != S; i = t[i])
{
cap[t[i]][i] -= flow;
cap[i][t[i]] += flow;
}
flowmax += flow * dist[D];
return 1;
}
int main()
{
fin >> n >> m >> S >> D;
int x, y, z, cc;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> z >> cc;
cap[x][y] = z;
cost[x][y] = cc;
cost[y][x] = -cc;
g[x].push_back(y);
g[y].push_back(x);
}
Bellman_Ford();
while (dijkstra());
fout << flowmax << "\n";
return 0;
}