Pagini recente » Cod sursa (job #3365014) | Cod sursa (job #3365019) | Cod sursa (job #3365010) | Cod sursa (job #3365003)
#include <bits/stdc++.h>
using namespace std;
ifstream f("cc.in");
ofstream g("cc.out");
int cost[400][400], n, dist[400], realdist[400], dist2[400], r[400][400], s, d, sol, flux=0, inq[400], tata[400], N;
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;
for (int i=1; i<=n; i++)
{
for (int j=n+1; j<=n+n; j++)
{
f >> cost[i][j];
cost[j][i]=-cost[i][j];
v[i].push_back(j);
v[j].push_back(i);
r[i][j]=1;
}
}
s=2*n+1, d=2*n+2;
N=2*n+2;
for (int i=1; i<=n; i++)
{
v[i].push_back(s);
v[s].push_back(i);
cost[i][s]=0;
r[s][i]=1;
r[i][s]=0;
}
for (int i=n+1; i<=n+n; i++)
{
v[i].push_back(d);
v[d].push_back(i);
cost[i][d]=0;
r[i][d]=1;
r[d][i]=0;
}
fmcm ();
g << sol;
}