Cod sursa(job #2627463)

Utilizator Data 10 iunie 2020 22:22:54 Traseu 20 cpp-64 done Arhiva de probleme 3.61 kb
``````#include<fstream>
#include<algorithm>
#include<vector>
#include<queue>
#define INF 2000000000
using namespace std;
ifstream f("traseu.in");
ofstream g("traseu.out");
vector<int>a[352];
int n,s,d,flux,sol,r[352][352],z[352][352],tata[352],dist[352],dist2[352],realdist[352],di[352][352],in[62],out[62],p[62],pp[62];
bool inq[352];
queue<int>q;
struct elem
{
int x,dist;
inline bool operator < (const elem &a) const
{
return dist>a.dist;
}
};
priority_queue<elem>pq;

inline bool dijkstra()
{
int i,l,Z;
elem p;
for(i=1;i<=n;i++)
dist[i]=INF,tata[i]=0;
pq.push({s,0});
dist[s]=0;
dist2[s]=0;
while(!pq.empty())
{
p=pq.top();
pq.pop();
if(p.dist==dist[p.x])
{
l=a[p.x].size();
for(i=0;i<l;i++)
{
Z=realdist[p.x]-realdist[a[p.x][i]]+z[p.x][a[p.x][i]];
if(r[p.x][a[p.x][i]]>0&&dist[a[p.x][i]]>dist[p.x]+Z)
{
dist[a[p.x][i]]=dist[p.x]+Z;
dist2[a[p.x][i]]=dist2[p.x]+z[p.x][a[p.x][i]];
tata[a[p.x][i]]=p.x;
pq.push({a[p.x][i],dist[a[p.x][i]]});
}
}
}
}
for(i=1;i<=n;i++)
realdist[i]=dist2[i];
return dist[d]!=INF;
}

inline void bellman_ford()
{
int i,l,p;
for(i=1;i<=n;i++)
realdist[i]=INF;
realdist[s]=0;
q.push(s);
inq[s]=1;
while(!q.empty())
{
p=q.front();
q.pop();
inq[p]=0;
l=a[p].size();
for(i=0;i<l;i++)
if(r[p][a[p][i]]>0&&realdist[a[p][i]]>realdist[p]+z[p][a[p][i]])
{
realdist[a[p][i]]=realdist[p]+z[p][a[p][i]];
if(inq[a[p][i]]==0)
{
q.push(a[p][i]);
inq[a[p][i]]=1;
}
}
}
}

inline void fmcm()
{
int i,flow,cost;
bellman_ford();
while(dijkstra()!=0)
{
flow=INF;
for(i=d;i!=s;i=tata[i])
{
flow=min(flow,r[tata[i]][i]);
if(flow==0)
break;
}
if(flow!=0&&flow!=INF)
{
cost=0;
for(i=d;i!=s;i=tata[i])
{
r[tata[i]][i]-=flow;
r[i][tata[i]]+=flow;
cost+=z[tata[i]][i];
}
flux+=flow;
sol+=flow*cost;
}
}
}

int main()
{
int m,i,x,y,zz,j,k,k1=0,k2=0;
f>>n>>m;
for(i=1;i<=m;i++)
{
f>>x>>y>>zz;
sol+=zz;
di[x][y]=zz;
di[y][x]=zz;
in[y]++;
out[x]++;
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(di[i][k]!=0&&di[k][j]!=0&&(di[i][k]+di[k][j]<di[i][j]||(di[i][j]==0&&i!=j)))
di[i][j]=di[i][k]+di[k][j];
for(i=1;i<=n;i++)
if(in[i]>out[i])
p[++k1]=i;
else
if(out[i]>in[i])
pp[++k2]=i;
s=k1+k2+1;
d=k2+k2+2;
for(i=1;i<=k1;i++)
{
a[s].push_back(p[i]);
a[p[i]].push_back(s);
r[s][p[i]]=in[p[i]]-out[p[i]];
}
for(i=1;i<=k2;i++)
{
a[pp[i]].push_back(d);
a[d].push_back(pp[i]);
r[pp[i]][d]=out[pp[i]]-in[pp[i]];
}
for(i=1;i<=k1;i++)
for(j=1;j<=k2;j++)
{
x=p[i];
y=pp[j];
zz=di[x][y];
a[x].push_back(y);
a[y].push_back(x);
r[x][y]=INF;
z[x][y]=zz;
z[y][x]=-zz;
}
n+=2;
fmcm();
g<<sol;
return 0;
}
``````