Pagini recente » Cod sursa (job #3227272) | Cod sursa (job #2232575) | Cod sursa (job #316684) | Cod sursa (job #2131177) | Cod sursa (job #2358016)
#include <fstream>
#include <vector>
#include <deque>
using namespace std;
ifstream fin( "fmcm.in" );
ofstream fout( "fmcm.out" );
const int NMAX = 360;
const int INF = 2000000000;
int N, M;
int source, sink;
vector <int> Ad[NMAX];
int flow[NMAX][NMAX];
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
int parent[NMAX];
void Read()
{
fin >> N >> M;
fin >> source >> sink;
int x, y, c, lei;
for( int i = 1; i <= M; ++i )
{
fin >> x >> y >> c >> lei;
Ad[x].push_back(y);
Ad[x].push_back(x);
cap[x][y] = c;
cost[x][y] = lei;
cost[y][x] = -lei;
}
fin.close();
}
bool Bf()
{
deque <int> Q;
int d[NMAX];
bool in_q[NMAX] = { 0 };
for( int i = 1; i <= NMAX; ++i )
d[i] = INF,
parent[i] = 0;
d[source] = 0;
Q.push_back( source );
in_q[source] = true;
int w, u;
int mzg = 0;
while( !Q.empty() )
{
u = Q.front();
Q.pop_front();
in_q[u] = 0;
for( int i = 0; i < Ad[u].size(); ++i )
{
w = Ad[u][i];
if( cap[u][w] - flow[u][w] > 0 && d[w] > d[u] + cost[u][w] )
{
d[w] = d[u] + cost[u][w];
parent[w] = u;
if( !in_q[w] )
{
Q.push_back( w );
in_q[w] = true;
}
}
}
}
if( d[sink] == INF ) return false;
else return true;
}
void Do()
{
int cost_total = 0;
int curent_flow;
while( Bf() )
{
curent_flow = INF;
// if( parent[sink] == 0 ) continue;
for( int nod = sink; nod != source; nod = parent[nod] )
curent_flow = min( curent_flow, cap[ parent[nod] ][nod] - flow[ parent[nod] ][ nod ] );
for( int nod = sink; nod != source; nod = parent[nod] )
{
flow[ parent[nod]][ nod ] += curent_flow;
flow[ nod ][ parent[nod]] -= curent_flow;
cost_total += curent_flow * cost[ parent[nod] ][nod];
}
}
fout << cost_total << '\n';
}
int main()
{
Read();
Do();
return 0;
}