Pagini recente » Cod sursa (job #1555009) | Cod sursa (job #1396381) | Cod sursa (job #2456641) | Cod sursa (job #2456293) | Cod sursa (job #370808)
Cod sursa(job #370808)
#include <fstream>
#include <vector>
#include <list>
#include <cstring>
#define MAX 400
#define INFINIT 2000000000
using namespace std;
ifstream fi("fmcm.in");
ofstream fo("fmcm.out");
int Dist[MAX],C[MAX][MAX],F[MAX][MAX],sursa,dest,poz[MAX],heap[MAX],T[MAX];
vector<pair<int,int> > G[MAX],Gi[MAX];
int DHeap,N,M;
list<int> Q;
void citire(){
fi>>N>>M>>sursa>>dest;
int a,b,c,d;
for (int i=1;i<=M;++i){
fi>>a>>b>>c>>d;
C[a][b]=c;
G[a].push_back(make_pair(b,d));
G[b].push_back(make_pair(a,-d));
Gi[a].push_back(make_pair(b,d));
}
}
void bellman(){
for (int i=1;i<=N;++i) Dist[i]=INFINIT;
Q.push_back(sursa);
Dist[sursa]=0;
while (!Q.empty()){
list<int>::iterator it=Q.begin();
for (unsigned int i=0;i<G[*it].size();++i) if (C[*it][G[*it][i].first]-F[*it][G[*it][i].first]>0)
if (Dist[*it]+G[*it][i].second<Dist[G[*it][i].first]){
Dist[G[*it][i].first]=Dist[*it]+G[*it][i].second;
Q.push_back(G[*it][i].first);
}
Q.pop_front();
}
}
void swap(int i,int j){
int aux=heap[i];
heap[i]=heap[j];
heap[j]=aux;
poz[heap[i]]=i;
poz[heap[j]]=j;
}
void heap_up(int nod){
int dad=nod/2;
if (dad && Dist[heap[dad]]>Dist[heap[nod]]){
swap(nod,dad);
heap_up(dad);
}
}
void heap_dw(int nod){
int l=nod*2,r=l+1,minim=nod;
if (l<=DHeap && Dist[heap[l]]<Dist[heap[minim]]) minim=l;
if (r<=DHeap && Dist[heap[r]]<Dist[heap[minim]]) minim=r;
if (minim!=nod){
swap(nod,minim);
heap_dw(minim);
}
}
int dijkstra(){
DHeap=N;
for (int i=1;i<=N;++i){
heap[i]=i;
poz[i]=i;
Dist[i]=INFINIT;
}
Dist[sursa]=0;
memset(T,0,sizeof(T));
heap_up(poz[sursa]);
for (int i=1;i<N;++i){
int nod=heap[1];
swap(1,DHeap);
--DHeap;
heap_dw(1);
if (Dist[nod]!=INFINIT){
for (unsigned int j=0;j<G[nod].size();++j) if (C[nod][G[nod][j].first]-F[nod][G[nod][j].first]>0) {
if(Dist[G[nod][j].first]>Dist[nod]+G[nod][j].second){
Dist[G[nod][j].first]=Dist[nod]+G[nod][j].second;
T[G[nod][j].first]=nod;
}
heap_up(poz[G[nod][j].first]);
}
}
}
if (Dist[dest]==INFINIT) return 0; else return 1;
}
void reconst(){
for (int i=1;i<=N;++i)
for (unsigned int j=0;j<G[i].size();++j)
if (Dist[i]!=INFINIT && Dist[G[i][j].first]!=INFINIT) G[i][j].second+=Dist[i]-Dist[G[i][j].first];
}
void flow(){
bellman();
for (reconst();dijkstra();reconst()){
int maxflow=INFINIT;
for (int nod=dest;T[nod];nod=T[nod]) maxflow=min(maxflow,C[T[nod]][nod]-F[T[nod]][nod]);
if (maxflow)
for (int nod=dest;T[nod];nod=T[nod]) { F[T[nod]][nod]+=maxflow; F[nod][T[nod]]-=maxflow; }
}
int scost=0;
for (int i=1;i<=N;++i)
for (unsigned int j=0;j<Gi[i].size();++j){
scost+=F[i][Gi[i][j].first]*Gi[i][j].second;
}
fo<<scost<<"\n";
}
int main(){
citire();
flow();
fi.close();fo.close();
return 0;
}