Pagini recente » Cod sursa (job #383867) | Cod sursa (job #2053938) | Cod sursa (job #1449110) | Cod sursa (job #97913) | Cod sursa (job #2392807)
/*
** Code by Andrei Arhire
** Tecuci , Galati
*/
#include <bits/stdc++.h>
#define pb push_back
#define s second
#define f first
#define it vector < int > :: iterator
using namespace std ;
const int NR = 355 , oo = ( 1 << 30 ) ;
ifstream in ("fmcm.in") ;
ofstream out ("fmcm.out") ;
int n , m , source , sink , capacity , z , x , y ;
int64_t ans ;
int cost [ NR ][ NR ] , cap [ NR ][ NR ] , t [ NR ] ;
vector < int > v [ NR ] , d_old ( NR , oo ) , d_dij ( NR , oo ) , d_new ( NR , oo ) ;
struct cmp {
inline bool operator ()( int i , int j ) {
return d_dij [ i ] > d_dij [ j ] ;
}
};
priority_queue < int , vector < int > , cmp > q ;
bitset < NR > inq ;
bool dijkstra ( ) {
int nod , i , flow ;
for ( i = 1 ; i <= n ; ++ i ) d_dij [ i ] = oo ;
d_dij [ source ] = 0 ;
d_new [ source ] = 0 ;
q.push( source ) ;
while ( !q.empty() ) {
nod = q.top() ;
q.pop() ;
inq [ nod ] = 0 ;
for ( it i = v [ nod ].begin() ; i < v [ nod ].end() ; ++ i ) {
if ( cap [ nod ][ *i ] ) {
if ( d_dij [ nod ] + ( d_old [ nod ] + cost [ nod ][ *i ] - d_old [ *i ] ) < d_dij [ *i ] ) {
d_dij [ *i ] = d_dij [ nod ] + ( d_old [ nod ] + cost [ nod ][ *i ] - d_old [ *i ] ) ;
d_new [ *i ] = d_new [ nod ] + cost [ nod ][ *i ] ;
t [ *i ] = nod ;
if ( !inq [ *i ] )
q.push( *i ) ,
inq [ *i ] = 1 ;
}
}
}
}
if ( d_dij [ sink ] == oo ) return 0 ;
flow = oo ;
for ( i = sink ; i != source ; i = t [ i ] )
flow = min ( flow , cap [ t [ i ] ][ i ] ) ;
for ( i = sink ; i != source ; i = t [ i ] )
cap [ t [ i ] ][ i ] -= flow ,
cap [ i ][ t [ i ] ] += flow ;
for ( i = 1 ; i <= n ; ++ i ) d_old [ i ] = d_new [ i ] ;
ans += flow * d_new [ sink ] ;
return 1 ;
}
void bellman ( ) {
int nod ;
d_old [ source ] = 0 ;
queue < int > q ;
q.push( source ) ;
while ( !q.empty() ) {
nod = q.front() ;
q.pop() ;
inq [ nod ] = 0 ;
for ( it i = v [ nod ].begin() ; i != v [ nod ].end() ; ++ i ) {
if ( cap [ nod ][ *i ] )
if ( d_old [ nod ] + cost [ nod ][ *i ] < d_old [ *i ] ) {
d_old [ *i ] = d_old [ nod ] + cost [ nod ][ *i ] ;
if ( !inq [ *i ] )
q.push( *i ) ,
inq [ *i ] = 1 ;
}
}
}
}
int main () {
in >> n >> m >> source >> sink ;
while ( m -- ) {
in >> x >> y >> capacity >> z ;
cap [ x ][ y ] = capacity ;
cost [ x ][ y ] = z ;
cost [ y ][ x ] = -z ;
v [ x ].pb ( y ) ;
v [ y ].pb ( x ) ;
}
bellman() ;
while ( dijkstra() ) ;
out << ans ;
}