Pagini recente » Cod sursa (job #1293547) | Istoria paginii utilizator/dianaschneider | Cod sursa (job #1539671) | Cod sursa (job #2452129) | Cod sursa (job #410614)
Cod sursa(job #410614)
#include <queue>
#include <vector>
#include <fstream>
#define Nmax 351
#define INF 0x3f3f3f3f
/*
*
*/
using namespace std;
int N, NH, S, source, sink; // N- numer of vertexes, NH- Heap length, S-sum, source,sink- the source/sink(end) of the network
int H[Nmax], P[Nmax], d[Nmax], father[Nmax];// H- heap, P- position in heap, d[vertex]- distance from source to vertex, father[vertex]- the father of vertex
int C[Nmax][Nmax], Cost[Nmax][Nmax];
vector< vector< int > > G; //list of adjance
vector< int >::const_iterator it, iend;
void DownHeap( int k )
{
int son;
for( ; ; )
{
son=2*k;
if( son > NH )
return;
if( son < NH && d[H[son]] > d[H[son+1]] )
++son;
if( d[H[son]] >= d[H[k]] )
return;
swap( P[H[k]], P[H[son]]);
swap( H[k], H[son] );
k=son;
}
}
void UpHeap( int k )
{
int key=d[H[k]], f=k/2;
while( k > 1 && key < d[H[f]] )
{
swap( P[H[k]], P[H[f]] );
swap( H[k], H[f] );
k=f;
f/=2;
}
}
inline int pop( void )
{
int r=H[1];
P[H[1]]=P[H[NH]];
H[1]=H[NH--];
DownHeap( 1 );
return r;
}
inline void push( int k )
{
H[++NH]=k;
P[k]=NH;
UpHeap( NH );
}
void doo( void )
{
for( int i=0; i < N; ++i )
if( INF != d[i] )
for( it=G[i].begin(), iend=G[i].end(); it < iend; ++it )
if( INF != d[*it] )
Cost[i][*it]+=d[i]-d[*it];
}
void BellmanFord( void )
{
int x;
queue< int > Q;
vector< bool > inQ( N );
fill( d, d+N, INF );
d[source]=0;
Q.push( source );
inQ[source]=true;
while( !Q.empty() )
{
x=Q.front(); Q.pop();
for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
if( C[x][*it] > 0 && d[x]+Cost[x][*it] < d[*it] )
{
d[*it]=d[x]+Cost[x][*it];
if( !inQ[*it] )
{
Q.push( *it );
inQ[*it]=true;
}
}
}
S=d[sink];
}
int find_path( void )
{
doo();
int x, min_c;
for( NH=x=0; x < N; ++x )
{
d[x]=INF;
father[x]=-1;
H[x]=P[x]=0;
}
d[source]=0;
push( source );
while( NH )
{
x=pop();
P[x]=0;
for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
if( C[x][*it] > 0 && d[x]+Cost[x][*it] < d[*it] )
{
father[*it]=x;
d[*it]=d[x]+Cost[x][*it];
if( 0 == P[*it] )
push( *it );
else push( P[*it] );
}
}
if( -1 == father[sink] )
return 0;
father[source]=-1;
min_c=C[ father[sink] ][ sink ];
for( x=father[sink]; -1 != father[x]; x=father[x] )
min_c=min( min_c, C[ father[x] ][ x ] );
for( x=sink; -1 != father[x]; x=father[x] )
{
C[father[x]][x]-=min_c;
if( !C[x][father[x]] )
{
G[x].push_back( father[x] );
Cost[x][father[x]]=-Cost[father[x]][x];
}
C[x][father[x]]+=min_c;
}
S+=d[sink];
return S*min_c;
}
int main( void )
{
int M, x, y;
ifstream in( "fmcm.in" );
in>>N>>M>>source>>sink;
--source, --sink;
G.resize(N);
for( ; M; --M )
{
in>>x>>y;
--x, --y;
in>>C[x][y]>>Cost[x][y];
G[x].push_back( y );
}
for( x=0, M=find_path(); M; x+=M, M=find_path() );
ofstream out( "fmcm.out" );
out<<x;
return 0;
}