Pagini recente » Cod sursa (job #1682569) | Cod sursa (job #168020) | Cod sursa (job #1276779) | Cod sursa (job #430835) | Cod sursa (job #409095)
Cod sursa(job #409095)
#include<iostream.h>
#include<fstream.h>
#define u (1<<30)
int ver[25999],leg[25999],cost[25999],c[359][359],d[359],h[359],hh[359],n,L,S,D,start[359],sum,rez,fa[359];
void bf()
{
int i,ok=1,t;
for(i=1;i<=n;i++)
d[i]=u;
d[S]=0;
while(ok)
{
ok=0;
for(i=1;i<=n;i++)
{
t=start[i];
while(t)
{
if(c[i][ver[t]]&&d[ver[t]]>d[i]+cost[t])
{
d[ver[t]]=d[i]+cost[t];
ok=1;
}
t=leg[t];
}
}
}
sum=d[D];
}
void percolate(int nod)
{
int safe=h[nod];
while(nod>1&&d[h[nod>>1]]>d[safe])
{
hh[h[nod>>1]]=nod;
h[nod]=h[nod>>1];
nod>>=1;
}
hh[safe]=nod;
h[nod]=safe;
}
int root()
{
int safe=h[1],son,ls,rs,nod=1;
hh[h[L]]=1;
h[1]=h[L--];
do
{
son=0;
ls=(nod<<1);
rs=1+ls;
if(ls<=L)
{
son=ls;
if(rs<=L&&d[h[rs]]<d[h[ls]])
son=rs;
if(d[h[son]]>=d[h[nod]])
son=0;
}
if(son)
{
hh[h[son]]=nod;
hh[h[nod]]=son;
ls=h[nod];
h[nod]=h[son];
h[son]=ls;
nod=son;
}
}
while(son);
hh[safe]=0;
return safe;
}
int dijkstra()
{
int i,t,min=u,nod;
for(i=1;i<=n;i++)
{
t=start[i];
while(t)
{
if(d[i]!=u&&d[ver[t]]!=u)
cost[t]+=d[i]-d[ver[t]];
t=leg[t];
}
}
for(i=1;i<=n;i++)
{
d[i]=u;
h[i]=hh[i]=i;
fa[i]=0;
}
d[S]=0;
hh[S]=h[S]=1;
hh[1]=h[1]=S;
L=n;
while(L)
{
nod=root();
t=start[nod];
while(t)
{
if(hh[ver[t]]&&c[nod][ver[t]]&&d[ver[t]]>d[nod]+cost[t])
{
d[ver[t]]=d[nod]+cost[t];
fa[ver[t]]=nod;
percolate(hh[ver[t]]);
}
t=leg[t];
}
}
if(d[D]!=u)
{
i=D;
while(i!=S)
{
if(min>c[fa[i]][i])
min=c[fa[i]][i];
i=fa[i];
}
i=D;
while(i!=S)
{
c[fa[i]][i]-=min;
c[i][fa[i]]+=min;
i=fa[i];
}
sum+=d[D];
rez+=min*sum;
return 1;
}
return 0;
}
int main()
{
int m,x,y,cap,z,q=0;
ifstream fin("fmcm.in");
ofstream g("fmcm.out");
fin>>n>>m>>S>>D;
while(m--)
{
fin>>x>>y>>cap>>z;
ver[++q]=y;
leg[q]=start[x];
start[x]=q;
c[x][y]=cap;
cost[q]=z;
ver[++q]=x;
leg[q]=start[y];
start[y]=q;
cost[q]=-z;
}
bf();
while(dijkstra());
g<<rez;
return 0;
}