Pagini recente » Cod sursa (job #1825822) | Cod sursa (job #1163773)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int Nmax = 603;
const int inf = 1e9;
struct NODE
{
int nod;
int dist;
NODE( const int a = 0, const int b = 0 ) : nod( a ), dist( b ) {}
bool operator < ( const NODE X ) const
{
return dist > X.dist;
}
};
vector <int> G[Nmax];
priority_queue <NODE> MinHeap;
int C[Nmax][Nmax];
int F[Nmax][Nmax];
int indice[Nmax][Nmax];
int Cost[Nmax][Nmax];
int dist[Nmax], tata[Nmax], in_q[Nmax], coada[Nmax];
int N, M, DIM, E;
void BellmanFord( int S, int D )
{
for ( int i = 0; i <= DIM; ++i )
{
dist[i] = inf;
in_q[i] = 0;
}
int st, dr;
coada[st = dr = 1] = S;
in_q[S] = 0;
dist[S] = 0;
while ( st <= dr )
{
int nod = coada[ st++ ];
in_q[nod] = 0;
for ( auto x: G[nod] )
{
if ( dist[x] > dist[nod] + Cost[nod][x] && C[nod][x] > F[nod][x] )
{
dist[x] = dist[nod] + Cost[nod][x];
if ( !in_q[x] )
{
in_q[x] = 1;
coada[ ++dr ] = x;
}
}
}
}
}
void init( int S, int D )
{
for ( int i = 0; i <= DIM; ++i )
{
for ( auto x: G[i] )
{
if ( dist[i] != inf && dist[x] != inf )
{
Cost[i][x] += dist[i] - dist[x];
}
}
}
for ( int i = 0; i <= DIM; ++i )
{
dist[i] = inf;
tata[i] = 0;
}
dist[S] = 0;
}
int Dijkstra( int S, int D )
{
init( S, D );
MinHeap.push( NODE( S, 0 ) );
while ( MinHeap.size() )
{
int nod = MinHeap.top().nod;
int ddd = MinHeap.top().dist;
MinHeap.pop();
if ( dist[nod] != ddd ) continue;
for ( auto x: G[nod] )
{
if ( dist[x] > dist[nod] + Cost[nod][x] && C[nod][x] > F[nod][x] )
{
dist[x] = dist[nod] + Cost[nod][x];
tata[x] = nod;
MinHeap.push( NODE( x, dist[x] ) );
}
}
}
return ( dist[D] < inf );
}
void MinCostMaxFlow( int S, int D, ostream &g )
{
int flow = 0, fmin, distD = dist[D], costFlow = 0;
while ( Dijkstra( S, D ) )
{
fmin = inf;
for ( int nod = D; nod != S; nod = tata[nod] )
fmin = min( fmin, C[ tata[nod] ][nod] - F[ tata[nod] ][nod] );
for ( int nod = D; nod != S; nod = tata[nod] )
{
F[ tata[nod] ][nod] += fmin;
F[nod][ tata[nod] ] -= fmin;
}
flow += fmin;
distD += dist[D];
costFlow += distD * fmin;
}
g << flow << " " << costFlow << "\n";
for ( int i = 1; i <= N; ++i )
for ( int j = N + 1; j <= N + M; ++j )
if ( F[i][j] == 1 )
g << indice[i][j] << " ";
}
void add_edge( int x, int y, int cap, int cost, int ind )
{
G[x].push_back( y );
G[y].push_back( x );
indice[x][y] = indice[y][x] = ind;
C[x][y] = cap;
Cost[x][y] = +cost;
Cost[y][x] = -cost;
}
int main()
{
ifstream f("cmcm.in");
ofstream g("cmcm.out");
f >> N >> M >> E;
int S = 0, D = N + M + 1;
for ( int i = 1, a, b, c; i <= E; ++i )
{
f >> a >> b >> c;
add_edge( a, b + N, 1, c, i );
}
for ( int i = 1; i <= N; ++i )
add_edge( S, i, 1, 0, 0 );
for ( int i = N + 1; i <= N + M; ++i )
add_edge( i, D, 1, 0, 0 );
DIM = N + M + 1;
BellmanFord( S, D );
MinCostMaxFlow( S, D, g );
return 0;
}