Pagini recente » Cod sursa (job #2030653) | Borderou de evaluare (job #3365087) | Borderou de evaluare (job #3364653) | Monitorul de evaluare | Cod sursa (job #3365087)
#include <bits/stdc++.h>
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
struct nod
{
int x, poz;
};
int cost[25000], n, dist[400], realdist[400], dist2[400], r[25400], s, d, sol, flux=0, inq[400];
vector <nod> v[400];
nod tata[400];
struct elem
{
int x, dist;
bool operator < (const elem & other) const
{
return dist>other.dist;
}
};
priority_queue <elem> pq;
bool dijk ()
{
for (int i=1; i<=n; i++)
dist[i]=1e9, tata[i]={0,0};
dist[s]=dist2[s]=0;
pq.push({s,0});
while (!pq.empty())
{
elem a=pq.top();
pq.pop();
if (a.dist==dist[a.x])
{
for (auto y:v[a.x])
{
int dif=realdist[a.x]-realdist[y.x]+cost[y.poz];
if (r[y.poz]>0 && dist[y.x]>dist[a.x]+dif)
{
dist[y.x]=dist[a.x]+dif;
dist2[y.x]=dist2[a.x]+cost[y.poz];
tata[y.x].x=a.x;
tata[y.x].poz=y.poz;
pq.push({y.x, dist[y.x]});
}
}
}
}
for (int i=1; i<=n; i++)
realdist[i]=dist2[i];
return (dist[d]!=1e9);
}
void bellman ()
{
queue <int> q;
for (int i=1; i<=n; i++)
realdist[i]=1e9;
realdist[s]=0;
q.push (s);
inq[s]=1;
while (!q.empty())
{
int nod=q.front();
q.pop();
inq[nod]=0;
for (auto y:v[nod])
{
if (r[y.poz]>0 && realdist[y.x]>realdist[nod]+cost[y.poz])
{
realdist[y.x]=realdist[nod]+cost[y.poz];
if (!inq[y.x])
{
q.push(y.x);
inq[y.x]=1;
}
}
}
}
}
void fmcm ()
{
bellman ();
while (dijk())
{
int flow=1e9;
for (int i=d; i!=s; i=tata[i].x)
{
flow=min (flow, r[tata[i].poz]);
if (!flow)
break;
}
if (flow!=1e9 && flow)
{
int cs=0;
for (int i=d; i!=s; i=tata[i].x)
{
r[tata[i].poz]-=flow;
r[tata[i].poz^1]+=flow;
cs+=cost[tata[i].poz];
}
flux+=flow;
sol+=cs*flow;
}
}
}
signed main ()
{
int m, k=0;
f >> n >> m >> s >> d;
while (m--)
{
int x, y, c, p;
f >> x >> y >> c >> p;
r[k]=c;
cost[k]=p;
v[x].push_back({y, k});
k++;
r[k]=0;
v[y].push_back({x, k});
cost[k]=-p;
k++;
}
fmcm ();
g << sol;
}