Pagini recente » Cod sursa (job #629177) | Cod sursa (job #3265023) | Cod sursa (job #1965387) | Cod sursa (job #1099194) | Cod sursa (job #604722)
Cod sursa(job #604722)
#include <iostream>
#include <vector>
#include <queue>
#define NMax 400
#define Inf 2000000000
using namespace std;
vector <int> G[NMax];
int N, Cost[NMax][NMax], S, D, Dist[NMax], Father[NMax], DistD;
int Cap[NMax][NMax], Flow[NMax][NMax], CostFM;
void Read ()
{
freopen ("fmcm.in", "r", stdin);
int M;
scanf ("%d %d %d %d", &N, &M, &S, &D);
for (; M>0; --M)
{
int X, Y, Z, Q;
scanf ("%d %d %d %d", &X, &Y, &Z, &Q);
G[X].push_back (Y);
Cap[X][Y]=Z;
Cost[X][Y]=Q;
G[Y].push_back (X);
Cost[Y][X]=-Q;
}
}
void Print ()
{
freopen ("fmcm.out", "w", stdout);
printf ("%d\n", CostFM);
}
inline int Min (int a, int b)
{
if (a<b)
{
return a;
}
return b;
}
bool BellmanFord (int Start)
{
queue <int> Q;
bool InQ[NMax];
for (int i=1; i<=N; ++i)
{
Dist[i]=Inf;
InQ[i]=false;
}
Dist[Start]=0;
Q.push (Start);
InQ[Start]=true;
while (!Q.empty ())
{
int X=Q.front ();
Q.pop ();
InQ[X]=false;
for (unsigned i=0; i<G[X].size (); ++i)
{
int V=G[X][i];
int C=Cost[X][V];
if (Dist[X]+C<Dist[V] and Cap[X][V]-Flow[X][V]>0)
{
Dist[V]=Dist[X]+C;
Father[V]=X;
if (!InQ[V])
{
Q.push (V);
InQ[V]=true;
}
}
}
}
if (Dist[D]!=Inf)
{
return true;
}
return false;
}
void EdmondsKarp ()
{
BellmanFord (S);
int CurrentFlow=Inf;
do
{
for (int X=D; X!=S; X=Father[X])
{
CurrentFlow=Min (CurrentFlow, Cap[Father[X]][X]-Flow[Father[X]][X]);
}
for (int X=D; X!=S; X=Father[X])
{
Flow[Father[X]][X]+=CurrentFlow;
Flow[X][Father[X]]-=CurrentFlow;
}
DistD+=Dist[D];
CostFM+=(CurrentFlow*Dist[D]);
}
while (BellmanFord (S));
}
int main()
{
Read ();
EdmondsKarp ();
Print ();
return 0;
}