Pagini recente » Cod sursa (job #2808890) | Cod sursa (job #1661949) | Cod sursa (job #2402498) | Cod sursa (job #958760) | Cod sursa (job #360824)
Cod sursa(job #360824)
#include <algorithm>
#include <vector>
using namespace std;
#define DIM 355
#define pb push_back
#define oo 1<<31-1
vector <int> lst[DIM];
int c[DIM][DIM],f[DIM][DIM],ct[DIM][DIM];
int q[DIM*DIM],viz[DIM],t[DIM],dist[DIM],h[DIM],poz[DIM],lim[DIM];
int n,m,s,d,minim,sum,l;
long long cost;
void read ()
{
int i,x,y,z,t;
scanf ("%d%d%d%d",&n,&m,&s,&d);
for (i=1; i<=m; ++i)
{
scanf ("%d%d%d%d",&x,&y,&z,&t);
lst[x].pb (y);
lst[y].pb (x);
c[x][y]=z;
ct[x][y]=t;
ct[y][x]=-t;
}
}
inline void init ()
{
int i;
for (i=1; i<=n; ++i)
{
t[i]=viz[i]=0;
dist[i]=oo;
h[i]=poz[i]=i;
}
}
void bellman_ford ()
{
int i,st,dr;
for (i=1; i<=n; ++i)
lim[i]=(int)lst[i].size ();
init ();
for (dist[q[st=dr=1]=s]=0; st<=dr; viz[q[st++]]=0)
for (i=0; i<lim[st]; ++i)
if (c[q[st]][lst[st][i]]>f[q[st]][lst[st][i]] && dist[q[st]]+ct[q[st]][lst[st][i]]<dist[lst[st][i]])
{
dist[lst[st][i]]=dist[q[st]]+ct[q[st]][lst[st][i]];
t[lst[st][i]]=q[st];
if (!viz[lst[st][i]])
viz[q[++dr]=lst[st][i]]=1;
}
sum=dist[d];
}
inline void swap (int &a,int &b)
{
int aux=a;
a=b;
b=aux;
}
inline void upheap (int x)
{
for ( ; x/2>1 && dist[h[x]]<dist[h[x/2]]; x/=2)
{
swap (h[x],h[x/2]);
poz[h[x]]=x;
poz[h[x/2]]=x/2;
}
}
inline void downheap (int x)
{
int y;
for (y=0; x!=y; )
{
y=x;
if (y*2<=l && dist[h[x]]>dist[h[y*2]])
x=y*2;
if (y*2+1<=l && dist[h[x]]>dist[h[y*2+1]])
x=y*2+1;
swap (h[x],h[y]);
poz[h[x]]=x;
poz[h[y]]=y;
}
}
int dijkstra ()
{
int i,j;
for (i=1; i<=n; ++i)
for (j=0; j<lim[i]; ++j)
if (dist[i]!=oo && dist[lst[i][j]]!=oo)
ct[i][lst[i][j]]+=dist[i]-dist[lst[i][j]];
init ();
for (dist[h[poz[s]=1]=s]=0, h[poz[1]=s]=1, l=n; l>1 && dist[h[1]]!=oo; )
{
for (i=0; i<lim[h[1]]; ++i)
if (c[h[1]][lst[h[1]][i]]>f[h[1]][lst[h[1]][i]] && dist[h[1]]+ct[h[1]][lst[h[1]][i]]<dist[lst[h[1]][i]])
{
dist[lst[h[1]][i]]=dist[h[1]]+ct[h[1]][lst[h[1]][i]];
t[lst[h[1]][i]]=h[1];
upheap (poz[lst[h[1]][i]]);
}
poz[h[1]=h[l--]]=1;
if (l>1)
downheap (1);
}
if (dist[d]!=oo)
return 1;
return 0;
}
inline int min (int a,int b)
{
if (a<b)
return a;
return b;
}
void solve ()
{
int i;
for (minim=oo; dijkstra (); minim=oo)
{
for (i=d; i!=s; i=t[i])
minim=min (minim,c[t[i]][i]-f[t[i]][i]);
for (i=d; i!=s; i=t[i])
{
f[t[i]][i]+=minim;
f[i][t[i]]-=minim;
}
sum+=dist[d];
cost+=minim*sum;
}
printf ("%lld",cost);
}
int main ()
{
freopen ("fmcm.in","r",stdin);
freopen ("fmcm.out","w",stdout);
read ();
bellman_ford ();
solve ();
return 0;
}