Pagini recente » Cod sursa (job #910954) | Cod sursa (job #1131161) | Cod sursa (job #928193) | Cod sursa (job #2103901) | Cod sursa (job #469437)
Cod sursa(job #469437)
#include <stdio.h>
#include <vector>
using namespace std;
vector<int> graf[355];
vector<int>::iterator u;
int i,n,m,s,d,x,y,c,z,heap[355],poz[355],aux,first,difmin[355],cap[355][355],f[355][355],cost[355][355],tt[355];
long long dist[355],sol;
bool k;
inline void heap_up(int p)
{
while (p>1 && dist[heap[p]]<dist[heap[p>>1]])
{
aux=heap[p];
heap[p]=heap[p>>1];
heap[p>>1]=aux;
poz[heap[p]]=p;
poz[heap[p>>1]]=p>>1;
p>>=1;
}
}
inline void heap_down(int p)
{
int min;
while ((p*2<=x && dist[heap[p]]>dist[heap[p*2]]) || (p*2+1<=x && dist[heap[p]]>dist[heap[p*2+1]]))
{
if (p*2+1<=x)
if (dist[heap[p*2]]<dist[heap[p*2+1]])
min=p*2;
else
min=p*2+1;
else
min=p*2;
aux=heap[p];
heap[p]=heap[min];
heap[min]=aux;
poz[heap[p]]=p;
poz[heap[min]]=min;
p=min;
}
}
int main()
{
freopen("fmcm.in","r",stdin);
freopen("fmcm.out","w",stdout);
scanf("%d %d %d %d",&n,&m,&s,&d);
for (i=1;i<=m;++i)
{
scanf("%d %d %d %d",&x,&y,&c,&z);
graf[x].push_back(y);
cap[x][y]=c;
cost[x][y]=z;
graf[y].push_back(x);
cost[y][x]=-z;
}
k=true;
while (k)
{
k=false;
poz[1]=0;
dist[1]=1LL*13000*10000000;
for (i=2;i<=n;++i)
{
poz[i]=0;
dist[i]=dist[i-1];
}
x=1;
heap[1]=s;
poz[s]=1;
dist[s]=0;
difmin[s]=2147000000;
while (x)
{
first=heap[1];
if (first==d)
k=true;
poz[heap[1]]=0;
if (x==1)
x=0;
else
{
heap[1]=heap[x--];
poz[heap[1]]=1;
heap_down(1);
}
for (u=graf[first].begin();u!=graf[first].end();++u)
if (cap[first][*u]>f[first][*u] && dist[first]+cost[first][*u]<dist[*u])
{
if (difmin[first]<cap[first][*u]-f[first][*u])
difmin[*u]=difmin[first];
else
difmin[*u]=cap[first][*u]-f[first][*u];
dist[*u]=dist[first]+cost[first][*u];
tt[*u]=first;
if (poz[*u])
heap_up(poz[*u]);
else
{
heap[++x]=*u;
poz[heap[x]]=x;
heap_up(x);
}
}
}
if (k)
for (i=d;i!=s;i=tt[i])
{
f[tt[i]][i]+=difmin[d];
f[i][tt[i]]-=difmin[d];
sol+=difmin[d]*cost[tt[i]][i];
}
}
printf("%lld",sol);
return 0;
}