Pagini recente » Cod sursa (job #1968733) | Istoria paginii runda/pixelcup/clasament | Cod sursa (job #1836597) | Istoria paginii runda/ichb-scoala-2014-9/clasament | Cod sursa (job #990482)
Cod sursa(job #990482)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
const int Nmax = 202;
const int oo = 0x3f3f3f3f;
typedef pair<int,int> node;
vector <int> G[Nmax];
int F[Nmax][Nmax], C[Nmax][Nmax], Cost[Nmax][Nmax];
int dist[Nmax], old_dist[Nmax], real_dist[Nmax];
int tata[Nmax];
priority_queue < node, vector <node>, greater <node> > heap;
int N, S, D;
void read()
{
ifstream f("cc.in");
f >> N;
for ( int i = 1; i <= N; ++i )
{
for ( int j = 1; j <= N; ++j )
{
int a = i;
int b = j + N;
int c;
f >> c;
G[a].push_back( b );
G[b].push_back( a );
C[a][b] = 1;
Cost[a][b] = c;
Cost[b][a] = -c;
}
}
f.close();
}
void build_graph()
{
S = 0;
D = N + N + 1;
for ( int i = 1; i <= N; ++i )
{
G[S].push_back( i );
G[i].push_back( S );
C[S][i] = 1;
}
for ( int i = 1; i <= N; ++i )
{
G[i + N].push_back( D );
G[D].push_back( i + N );
C[i + N][D] = 1;
}
}
inline bool Dijkstra()
{
memset( dist, oo, sizeof( dist ) );
dist[S] = real_dist[S] = 0;
heap.push( node( 0, S ) );
while( !heap.empty() )
{
int nod = heap.top().second;
int val = heap.top().first;
heap.pop();
if( dist[nod] != val )
continue;
for( unsigned i = 0; i < G[nod].size(); i++ )
{
int son = G[nod][i];
if( C[nod][son] > F[nod][son] )
{
int cost = dist[nod] + Cost[nod][son] + old_dist[nod] - old_dist[son];
if( cost < dist[son] )
{
tata[son] = nod;
dist[son] = cost;
real_dist[son] = real_dist[nod] + Cost[nod][son];
heap.push( node( dist[son], son ) );
}
}
}
}
memcpy( old_dist, real_dist, sizeof( old_dist ) );
return ( dist[D] != oo );
}
void Edmonds_Karp()
{
ofstream g("cc.out");
int flow = 0, cost_f = 0, nod;
while( Dijkstra() )
{
int fmin = oo;
for ( nod = D; nod != S; nod = tata[nod] )
fmin = min( fmin, C[ tata[nod] ][nod] - F[ tata[nod] ][nod] );
for ( nod = D; nod != S; nod = tata[nod] )
{
F[ tata[nod] ][nod] += fmin;
F[nod][ tata[nod] ] -= fmin;
}
flow += fmin;
cost_f += fmin * real_dist[D];
}
g << cost_f << "\n";
g.close();
}
int main()
{
read();
build_graph();
Edmonds_Karp();
return 0;
}