Mai intai trebuie sa te autentifici.
Cod sursa(job #3364653)
| Utilizator | Data | 8 septembrie 2026 16:16:09 | |
|---|---|---|---|
| Problema | Flux maxim de cost minim | Scor | 100 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 2.56 kb |
#include <bits/stdc++.h>
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
int cost[400][400], n, dist[400], realdist[400], dist2[400], r[400][400], s, d, sol, flux=0, inq[400], tata[400];
vector <int> v[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;
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]+cost[a.x][y];
if (r[a.x][y]>0 && dist[y]>dist[a.x]+dif)
{
dist[y]=dist[a.x]+dif;
dist2[y]=dist2[a.x]+cost[a.x][y];
tata[y]=a.x;
pq.push({y, dist[y]});
}
}
}
}
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[nod][y]>0 && realdist[y]>realdist[nod]+cost[nod][y])
{
realdist[y]=realdist[nod]+cost[nod][y];
if (!inq[y])
{
q.push(y);
inq[y]=1;
}
}
}
}
}
void fmcm ()
{
bellman ();
while (dijk())
{
int flow=1e9;
for (int i=d; i!=s; i=tata[i])
{
flow=min (flow, r[tata[i]][i]);
if (!flow)
break;
}
if (flow!=1e9 && flow)
{
int cs=0;
for (int i=d; i!=s; i=tata[i])
{
r[tata[i]][i]-=flow;
r[i][tata[i]]+=flow;
cs+=cost[tata[i]][i];
}
flux+=flow;
sol+=cs*flow;
}
}
}
signed main ()
{
int m;
f >> n >> m >> s >> d;
while (m--)
{
int x, y, c, p;
f >> x >> y >> c >> p;
v[x].push_back(y);
v[y].push_back(x);
r[x][y]+=c;
cost[x][y]+=p;
cost[y][x]-=p;
}
fmcm ();
g << sol;
}
