Pagini recente » Cod sursa (job #120827) | Cod sursa (job #2665287) | Cod sursa (job #370785) | Cod sursa (job #978264) | Cod sursa (job #2583023)
#include <bits/stdc++.h>
#define NMAX 109
#define INF 99999999
using namespace std;
ifstream fin("cc.in");
ofstream fout("cc.out");
vector<int>g[NMAX];
int n,m;
void citire();
int cost[NMAX][NMAX];
int c[NMAX][NMAX];
int d[NMAX];
int then[NMAX];
int now[NMAX];
int p[NMAX];
int start,dest;
priority_queue< pair<int,int>, vector<pair<int,int> >, greater< pair<int,int> > >H;
int sol;
bool djk();
void bellman();
int main()
{citire();
bellman();
while(djk());
fout<<sol;
return 0;
}
void citire()
{
fin>>n;
int i,j;
start=0;dest=2*n;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{int x;
fin>>x;
cost[i][n+j]=x;
cost[n+j][i]=-x;
c[i][n+j]=1;
g[i].push_back(j+n);
g[j+n].push_back(i);
}
for(i=1;i<=n;i++)
{
g[start].push_back(i);
g[i].push_back(start);
c[start][i]=1;
g[i+n].push_back(dest);
g[dest].push_back(i+n);
c[i+n][dest]=1;
}
}
bool djk()
{
int i;
for(i=0;i<=dest;i++)
d[i]=INF;
d[start]=0;
H.push({0,start});
now[start]=0;
while(!H.empty())
{
int act=H.top().second;
int costact=H.top().first;
H.pop();
if(costact!=d[act])
continue;
for(int i=0;i<g[act].size();i++)
{
int vec=g[act][i];
if(c[act][vec])
{
int now_d=d[act]+cost[act][vec]+then[act]-then[vec];
if(now_d< d[vec])
{
d[vec]=now_d;
now[vec]=now[act]+cost[act][vec];
H.push({ now_d,vec });
p[vec]=act;
}
}
}
}
if(d[dest]==INF)
return 0;
int ct;
int minim=INF;
int costact=0;
for(ct=dest;ct!=start;ct=p[ct])
{
minim=min(minim, c[p[ct]][ct]);
costact+=cost[ p[ct] ][ct];
}
for(ct=dest;ct!=start;ct=p[ct])
{
c[p[ct]][ct]-=minim;
}
for(ct=start;ct<=dest;ct++)
then[ct]=now[ct];
sol+=now[dest];
return 1;
}
void bellman(){
for(int i=1;i<=dest;i++)
then[i]=INF;
then[start]=0;
H.push({0,start});
while(!H.empty())
{
int act=H.top().second;
int costact=H.top().first;
H.pop();
if(costact!=then[act])continue;
for(int i=0;i<g[act].size();i++)
{
int vec=g[act][i];
if(c[act][vec])
{
if(then[vec]>then[act]+cost[act][vec])
{then[vec]=then[act]+cost[act][vec];
H.push({then[vec],vec});
}
}
}
}
}