Pagini recente » Cod sursa (job #1726658) | Cod sursa (job #967766) | Cod sursa (job #2571644) | Statistici Matei Raluca (raluq) | Cod sursa (job #2949503)
#include <cstdio>
#include <queue>
using namespace std;
struct Edge
{
int to;
int cap;
int cost;
int inv;
};
const int FN = 350 + 7;
const int FMAXDEG = FN;
const int INF = (int) 1e9 + 7;
int fln;
int fls;
int fld;
Edge fladj[FN][FMAXDEG];
int fltop[FN];
int fldist[FN];
bool flvis[FN];
int flparid[FN];
int flflow;
long long flflowcost;
queue<int> flq;
void flinit(int n, int s, int d)
{
fln = n;
fls = s;
fld = d;
flflow = 0;
flflowcost = 0;
for (int i = 1; i <= fln; i++)
{
fltop[i] = 0;
}
}
void fladdedge(int a, int b, int cap, int cost)
{
fltop[a]++;
fltop[b]++;
fladj[a][fltop[a]] = {b, cap, cost, fltop[b]};
fladj[b][fltop[b]] = {a, 0, -cost, fltop[a]};
}
bool flbellman()
{
for (int i = 1; i <= fln; i++)
{
fldist[i] = INF;
flvis[i] = 0;
}
flq.push(fls);
flvis[fls] = 1;
fldist[fls] = 0;
while (!flq.empty())
{
int a = flq.front();
flvis[a] = 0;
flq.pop();
for (int j = 1; j <= fltop[a]; j++)
{
if (fladj[a][j].cap > 0 && fldist[a] + fladj[a][j].cost < fldist[fladj[a][j].to])
{
fldist[fladj[a][j].to] = fldist[a] + fladj[a][j].cost;
flparid[fladj[a][j].to] = fladj[a][j].inv;
if (!flvis[fladj[a][j].to])
{
flvis[fladj[a][j].to] = 1;
flq.push(fladj[a][j].to);
}
}
}
}
if (fldist[fld] == INF)
{
return 0;
}
int mn = INF, v = fld, s = 0;
while (v != fls)
{
int cur = flparid[v];
mn = min(mn, fladj[fladj[v][cur].to][fladj[v][cur].inv].cap);
v = fladj[v][cur].to;
}
v = fld;
while (v != fls)
{
int cur = flparid[v];
fladj[fladj[v][cur].to][fladj[v][cur].inv].cap -= mn;
fladj[v][cur].cap += mn;
s += fladj[fladj[v][cur].to][fladj[v][cur].inv].cost;
v = fladj[v][cur].to;
}
flflow += mn;
flflowcost += 1LL * mn * fldist[fld];
return 1;
}
void flpumpflow()
{
while (flbellman())
{
}
}
signed main()
{
freopen ("fmcm.in", "r", stdin);
freopen ("fmcm.out", "w", stdout);
int n, m, s, d;
scanf("%d %d %d %d", &n, &m, &s, &d);
flinit(n, s, d);
for (int i = 1; i <= m; i++)
{
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
fladdedge(a, b, c, d);
}
flpumpflow();
printf("%lld\n", flflowcost);
return 0;
}
/**
**/