Pagini recente » Cod sursa (job #1306515) | Cod sursa (job #1088774) | Cod sursa (job #888626) | Cod sursa (job #2845344) | Cod sursa (job #1407799)
#include <bits/stdc++.h>
using namespace std;
const int Nmax = 360;
const int inf = 1e9;
struct NODE
{
int nod;
int dist;
NODE(){}
NODE( const int a = 0, const int b = 0 ) : nod( a ), dist( b ) {}
bool operator < ( const NODE &N ) const
{
return dist > N.dist;
}
};
vector <int> G[Nmax + 1];
priority_queue <NODE> MinHeap;
int Cost[Nmax + 1][Nmax + 1];
int C[Nmax + 1][Nmax + 1];
int F[Nmax + 1][Nmax + 1];
int tata[Nmax + 1], dist[Nmax + 1], in_q[Nmax + 1], coada[Nmax + 1];
int N, M;
void BellmanFord( int S, int D )
{
for ( int i = 1; i <= N; ++i )
{
dist[i] = inf;
}
int st, dr;
dist[S] = 0;
coada[st = dr = 1] = S;
in_q[S] = 1;
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 = 1; i <= N; ++i )
{
for ( auto x: G[i] )
{
if ( dist[x] != inf && dist[i] != inf )
{
Cost[i][x] += ( dist[i] - dist[x] );
}
}
}
for ( int i = 1; i <= N; ++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 );
}
long long Edmonds_Karp( int S, int D )
{
long long costFlow = 0;
long long flow = 0;
int fmin, distD = dist[D];
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 += fmin * distD;
}
return costFlow;
}
int main()
{
ifstream f("fmcm.in");
ofstream g("fmcm.out");
int S, D;
f >> N >> M >> S >> D;
for ( int i = 1, a, b, c, d; i <= M; ++i )
{
f >> a >> b >> c >> d;
G[a].push_back( b );
G[b].push_back( a );
C[a][b] = c;
Cost[a][b] = +d;
Cost[b][a] = -d;
}
BellmanFord( S, D );
g << Edmonds_Karp( S, D ) << "\n";
return 0;
}