Pagini recente » Cod sursa (job #1817713) | Cod sursa (job #485892) | Cod sursa (job #1223258) | Cod sursa (job #483938) | Cod sursa (job #410469)
Cod sursa(job #410469)
#include <queue>
#include <vector>
#include <fstream>
#define Nmax 351
#define INF 0x3f3f3f3f
/*
*
*/
using namespace std;
int N, NH, S, source, sink;
int C[Nmax][Nmax], Cost[Nmax][Nmax];
int H[Nmax], d[Nmax], c[Nmax], father[Nmax], Position[Nmax];
vector< vector< int > > G;
vector< int >::const_iterator it, iend;
inline void swap( int& x, int& y )
{
int aux=x;
x=y;
y=aux;
}
inline const int& min( const int& x, const int& y )
{
if( x < y )
return x;
return y;
}
void DownHeap( int k )
{
int son;
while( 1 )
{
son=2*k;
if( son > NH )
return;
if( son < NH && d[H[son]] > d[H[son+1]] )
++son;
if( d[H[k]] <= d[H[son]] )
return;
swap( Position[H[k]], Position[H[son]] );
swap( H[k], H[son] );
k=son;
}
}
void UpHeap( int k )
{
int key=d[H[k]], f=k/2;
while( f > 1 && key < d[H[f]] )
{
swap( Position[H[f]], Position[H[k]] );
swap( H[f], H[k] );
k=f;
f/=2;
}
}
inline int pop( void )
{
int r=H[1];
Position[H[1]]=Position[H[NH]];
H[1]=H[NH];
--NH;
DownHeap( 1 );
return r;
}
inline void push( int k )
{
H[++NH]=k;
Position[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();
inQ[x]=false;
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();
NH=0;
int x;
for( x=0; x < N; ++x )
{
d[x]=INF;
father[x]=-1;
H[x]=Position[x]=0;
}
d[source]=0;
c[source]=INF;
push( source );
while( NH )
{
x=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] )
{
father[*it]=x;
d[*it]=d[x]+Cost[x][*it];
c[*it]=min( c[x], C[x][*it] );
if( 0 == Position[*it] )
push( *it );
else UpHeap( Position[*it] );
}
}
if( -1 == father[sink] )
return INF;
father[source]=-1;
for( x=sink; -1 != father[x]; x=father[x] )
{
C[father[x]][x]-=c[sink];
if( 0 == C[x][father[x]] )
{
G[x].push_back( father[x] );
Cost[x][father[x]]=-Cost[father[x]][x];
}
C[x][father[x]]+=c[sink];
}
S+=d[sink];
return c[sink]*S;
}
int MaxFlowMinCut( void )
{
int path_c, s=0;
for( path_c=find_path(); INF != path_c; s+=path_c, path_c=find_path() );
return s;
}
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 );
}
ofstream out( "fmcm.out" );
out<<MaxFlowMinCut();
return 0;
}