Pagini recente » Cod sursa (job #2037655) | Cod sursa (job #360821)
Cod sursa(job #360821)
#include <stdio.h>
#define DIM 355
#define oo 1<<31-1
struct nod {int x;
nod *urm;} *lst[DIM];
int c[DIM][DIM],f[DIM][DIM],ct[DIM][DIM];
int q[10*DIM*DIM],viz[DIM],t[DIM],dist[DIM],h[DIM],poz[DIM];
int n,m,s,d,minim,sum,l;
long long cost;
void add (int x,int y)
{
nod *p=new nod;
p->x=x;
p->urm=lst[y];
lst[y]=p;
}
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);
add (x,y);
add (y,x);
c[x][y]=z;
ct[x][y]=t;
ct[y][x]=-t;
}
}
void init ()
{
int i;
for (i=1; i<=n; ++i)
{
t[i]=viz[i]=0;
dist[i]=oo;
h[i]=poz[i]=i;
}
}
int bellman_ford ()
{
int st,dr;
nod *p;
init ();
for (dist[q[st=dr=1]=s]=0; st<=dr; viz[q[st++]]=0)
for (p=lst[q[st]]; p; p=p->urm)
if (c[q[st]][p->x]>f[q[st]][p->x] && dist[q[st]]+ct[q[st]][p->x]<dist[p->x])
{
dist[p->x]=dist[q[st]]+ct[q[st]][p->x];
t[p->x]=q[st];
if (!viz[p->x])
viz[q[++dr]=p->x]=1;
}
sum=dist[d];
}
void swap (int &a,int &b)
{
int aux=a;
a=b;
b=aux;
}
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;
}
}
void downheap (int x)
{
int y,aux;
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 ()
{
nod *p;
int i,start;
for (i=1; i<=n; ++i)
for (p=lst[i]; p; p=p->urm)
if (dist[i]!=oo && dist[p->x]!=oo)
ct[i][p->x]+=dist[i]-dist[p->x];
init ();
for (dist[h[poz[s]=1]=s]=0, h[poz[1]=s]=1, l=n; l>1 && dist[h[1]]!=oo; )
{
for (p=lst[h[1]]; p; p=p->urm)
if (c[h[1]][p->x]-f[h[1]][p->x]>0 && dist[h[1]]+ct[h[1]][p->x]<dist[p->x])
{
dist[p->x]=dist[h[1]]+ct[h[1]][p->x];
t[p->x]=h[1];
upheap (poz[p->x]);
}
poz[h[1]=h[l--]]=1;
if (l>1)
downheap (1);
}
if (dist[d]!=oo)
return 1;
return 0;
}
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;
}