zkw費用流模板
阿新 • • 發佈:2019-02-06
void insert(int u,int v,int w,int cost) {add(u,v,w,cost); add(v,u,0,-cost);}
int spfa()
{
memset(mark,0,sizeof(mark));
rep(i,0,T) d[i]=inf;
int l=0,r=1;
q[l]=T;d[T]=0;mark[T]=1;
while (l^r)
{
int u=q[l++]; if (l==T) l=0; mark[u]=0;
for (int i=head[u];i;i=e[i].next)
if (e[i^1].w && d[u]-e[i].c<d[to])
{
d[to]=d[u]-e[i].c;
if (!mark[to])
{
mark[to]=1;
q[r++]=to;
if (r==T) r=0;
}
}
}
return d[0]==inf? 0:1;
}
int dfs(int x,int in)
{
if (x==T) return in;
mark[x]=1;
int w,used=0;
for (int i=head[x];i;i=e[i].next)
if (d[to]==d[x]-e[i].c && e[i].w && !mark[to])
{
used+=w=dfs(to,min(in-used,e[i].w));
ans+=w*e[i].c;
e[i].w-=w;e[i^1].w+=w;
if(used==in) return in;
}
return used;
}
void zkw()
{
while (spfa())
{
mark[T]=1;
while (mark[T])
{
memset(mark,0,sizeof(mark));
dfs(0,inf);
}
}
}
int spfa()
{
memset(mark,0,sizeof(mark));
rep(i,0,T) d[i]=inf;
int l=0,r=1;
q[l]=T;d[T]=0;mark[T]=1;
while (l^r)
{
int u=q[l++]; if (l==T) l=0; mark[u]=0;
for (int i=head[u];i;i=e[i].next)
if (e[i^1].w && d[u]-e[i].c<d[to])
{
d[to]=d[u]-e[i].c;
if (!mark[to])
{
mark[to]=1;
q[r++]=to;
if (r==T) r=0;
}
}
}
return d[0]==inf? 0:1;
}
int dfs(int x,int in)
{
if (x==T) return in;
mark[x]=1;
int w,used=0;
for (int i=head[x];i;i=e[i].next)
if (d[to]==d[x]-e[i].c && e[i].w && !mark[to])
{
used+=w=dfs(to,min(in-used,e[i].w));
ans+=w*e[i].c;
e[i].w-=w;e[i^1].w+=w;
if(used==in) return in;
}
return used;
}
void zkw()
{
while (spfa())
{
mark[T]=1;
while (mark[T])
{
memset(mark,0,sizeof(mark));
dfs(0,inf);
}
}
}