Pagini recente » Cod sursa (job #2678598) | Cod sursa (job #911950) | Cod sursa (job #875471) | Cod sursa (job #2518277) | Cod sursa (job #604742)
Cod sursa(job #604742)
#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 NHeap, Heap[NMax], Poz[NMax];
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;
}
inline void Swap (int X, int Y)
{
int Aux;
Aux=Poz[Heap[X]];
Poz[Heap[X]]=Poz[Heap[Y]];
Poz[Heap[Y]]=Aux;
Aux=Heap[X];
Heap[X]=Heap[Y];
Heap[Y]=Aux;
}
void Percolate (int X)
{
int F=(X>>1);
if (F>0 and Dist[Heap[X]]<Dist[Heap[F]])
{
Swap (X, F);
Percolate (F);
}
}
void Sift (int X)
{
int Son=(X<<1);
if (Son+1<=NHeap and Dist[Heap[Son+1]]<Dist[Heap[Son]])
{
++Son;
}
if (Son<=NHeap and Dist[Heap[Son]]<Dist[Heap[X]])
{
Swap (X, Son);
Sift (Son);
}
}
void Delete (int X)
{
Swap (X, NHeap);
Poz[Heap[NHeap]]=0;
Heap[NHeap]=0;
--NHeap;
Sift (X);
}
void Initialize (int Start)
{
for (int X=1; X<=N; ++X)
{
for (unsigned v=0; v<G[X].size (); ++v)
{
int V=G[X][v];
if (Dist[X]!=Inf and Dist[V]!=Inf)
{
Cost[X][V]+=(Dist[X]-Dist[V]);
}
}
}
NHeap=N;
for (int i=1; i<=N; ++i)
{
Dist[i]=Inf;
Heap[i]=Poz[i]=i;
Father[i]=0;
}
Dist[Start]=0;
Swap (1, Start);
}
bool Dijkstra (int Start, int End)
{
Initialize (Start);
while (NHeap>0)
{
int X=Heap[1];
Delete (1);
for (unsigned v=0; v<G[X].size (); ++v)
{
int V=G[X][v];
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;
Percolate (Poz[V]);
}
}
}
if (Dist[End]<Inf)
{
return true;
}
return false;
}
void EdmondsKarp ()
{
BellmanFord (S);
DistD=Dist[D];
while (Dijkstra (S, D))
{
int CurrentFlow=Inf;
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*DistD);
}
}
int main()
{
Read ();
EdmondsKarp ();
Print ();
return 0;
}