Pagini recente » Borderou de evaluare (job #1236554) | Borderou de evaluare (job #9937) | Borderou de evaluare (job #3332995) | Borderou de evaluare (job #10011) | Cod sursa (job #3364804)
#include <bits/stdc++.h>
using namespace std;
ifstream f("cmcm.in");
ofstream g("cmcm.out");
int cost[900][900], n, dist[900], realdist[900], dist2[900], r[900][900], s, d, sol, flux=0, inq[900], tata[900], N, m, q, idx[1000][1000];
vector <int> v[900];
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 ()
{
f >> n >> m >> q;
vector <pair <int,int>> edges;
for (int i=1; i<=q; i++)
{
int x, y, p;
f >> x >> y >> p;
y+=n;
v[x].push_back(y);
v[y].push_back(x);
r[x][y]=1;
idx[x][y]=i;
edges.push_back({x,y});
cost[x][y]=p;
cost[y][x]=-p;
}
s=n+m+1, d=n+m+2;
N=n+m+2;
//cout << N << ' ';
for (int i=1; i<=n; i++)
{
v[s].push_back(i);
v[i].push_back(s);
r[s][i]=1;
r[i][s]=0;
}
for (int i=n+1; i<=n+m; i++)
{
v[i].push_back(d);
v[d].push_back(i);
r[i][d]=1;
r[d][i]=0;
}
fmcm ();
g << flux << ' ' << sol<<'\n';
for (auto p:edges)
{
if (r[p.first][p.second]==0)
g << idx[p.first][p.second]<< ' ';
}
}