Pagini recente » Cod sursa (job #2727327) | Cod sursa (job #2159293) | Cod sursa (job #2629229) | Cod sursa (job #313668) | Cod sursa (job #1408126)
#include <bits/stdc++.h>
using namespace std;
const int Nmax = 350 + 1;
const int Mmax = 12500 + 1;
const int INF = numeric_limits<int>::max();
struct NODE
{
int nod;
int dist;
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];
queue<int> Q;
int N, M;
void BellmanFord( int S, int D )
{
for ( int i = 1; i <= N; ++i )
{
dist[i] = INF;
}
dist[S] = 0;
Q.push(S);
in_q[S] = 1;
while ( Q.size() )
{
int nod = Q.front();
Q.pop();
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;
Q.push(x);
}
}
}
}
}
void updateCosts()
{
for ( int i = 1; i <= N; ++i )
{
if (dist[i] != INF)
{
for (auto x: G[i])
if (dist[x] != INF)
Cost[i][x] += (dist[i] - dist[x]);
}
}
}
int Dijkstra(int S, int T)
{
updateCosts();
for ( int i = 1; i <= N; ++i )
{
dist[i] = INF;
tata[i] = 0;
}
dist[S] = 0;
MinHeap.push( {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( {x, dist[x]} );
}
}
}
return (dist[T] != 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;
}