Pagini recente » Cod sursa (job #2463448) | Cod sursa (job #2792946) | Cod sursa (job #141188) | Cod sursa (job #1624280) | Cod sursa (job #2849682)
#include <bits/stdc++.h>
using namespace std;
ifstream f("cc.in");
ofstream g("cc.out");
priority_queue <pair <int,int> , vector <pair <int,int>> , greater <pair <int,int>>> h;
int distanta[105],tata[105],cost[105][105],cap[105][105],flux[105][105];
vector <int> v[105];
int n,i,j,sursa,destinatie;
bool ok (int sursa,int destinatie)
{
int i;
for (i=sursa;i<=destinatie;i++)
{
distanta[i]=1e9;
}
tata[sursa]=0;
distanta[sursa]=0;
h.push({distanta[sursa],sursa});
while (!h.empty())
{
while (!h.empty()&&distanta[h.top().second]!=h.top().first)
{
h.pop();
}
if (h.empty())
{
break;
}
int acum = h.top().second;
h.pop();
for (int i=0;i<v[acum].size();i++)
{
int nod = v[acum][i];
if (cap[acum][nod]>flux[acum][nod])
{
if (distanta[nod]>distanta[acum]+cost[acum][nod])
{
tata[nod]=acum;
distanta[nod]=distanta[acum]+cost[acum][nod];
h.push({distanta[nod],nod});
}
}
}
}
if (distanta[destinatie]==1e9)
{
return 0;
}
return 1;
}
int main()
{
f>>n;
for (i=1;i<=n;i++)
{
for (j=1;j<=n;j++)
{
f>> cost[i][n+j];
cost[n+j][i] = -cost[i][n+j];
cap[i][n+j]=1;
v[i].push_back(n+j);
v[n+j].push_back(i);
}
}
sursa = 0 ;
destinatie = 2*n+1;
for (i=1;i<=n;i++)
{
cap[0][i]=1;
v[0].push_back(i);
v[i].push_back(0);
}
for (i=1;i<=n;i++)
{
cap[n+i][destinatie] = 1;
v[n+i].push_back(destinatie);
v[destinatie].push_back(n+i);
}
for (i=1;i<=destinatie;i++)
{
distanta[i]=1e9;
}
distanta[sursa]=0;
h.push({distanta[sursa],sursa});
while (!h.empty())
{
while (!h.empty()&&distanta[h.top().second]!=h.top().first)
{
h.pop();
}
if (h.empty())
{
break;
}
int acum = h.top().second;
h.pop();
for (int i=0;i<v[acum].size();i++)
{
int nod = v[acum][i];
if (cap[acum][nod]>flux[acum][nod])
{
if (distanta[nod]>distanta[acum]+cost[acum][nod])
{
distanta[nod]=distanta[acum]+cost[acum][nod];
h.push({distanta[nod],nod});
}
}
}
}
long long solfin =0;
while (ok(sursa,destinatie))
{
int nod = destinatie;
int sal = cap[tata[nod]][nod]-flux[tata[nod]][nod];
while (nod!=sursa)
{
sal = min (sal, cap[tata[nod]][nod]-flux[tata[nod]][nod]);
nod=tata[nod];
}
solfin =solfin +1LL*sal*distanta[destinatie];
nod = destinatie;
while (nod!=sursa)
{
flux[tata[nod]][nod]+=sal;
flux[nod][tata[nod]]-=sal;
nod=tata[nod];
}
}
g<<solfin;
return 0;
}