本文为较好封装的网络流板子,记得查看是否有爆长整型的可能,以及将 N,M 等全局变量设置正确。
实际使用的时候要先设置 n 的值,再调用 reset 清空,再用 add 加入所有边,最后调用 flow 得到答案。
struct Dicnic
{
int n,nd,s,t,hd[N],hu[N],lvl[N],qwq[N];
const int inf=(1u<<31)-1;
struct edge
{
int v,c,nt;
}e[M];
void reset()
{
fill(hd,hd+n,-1),nd=0;
}
void add(int u,int v,int c)
{
e[nd]={v,c,hd[u]},hd[u]=nd++,
e[nd]={u,0,hd[v]},hd[v]=nd++;
}
bool bfs()
{
int l=0,r=1;
fill(lvl,lvl+n,inf),copy(hd,hd+n,hu),qwq[0]=s,lvl[s]=0;
while(l<r)
for(int u=qwq[l++],z=hd[u],v;~z;z=e[z].nt)
if(e[z].c&&lvl[u]+1<lvl[v=e[z].v])
lvl[v]=lvl[u]+1,qwq[r++]=v;
return lvl[t]<inf;
}
int dfs(int u,int fl)
{
if(u==t)return fl;
int sm=0;
for(int &z=hu[u],v;~z;z=e[z].nt)
if(e[z].c&&lvl[u]+1==lvl[v=e[z].v])
{
int c=dfs(v,min(fl,e[z].c));
fl-=c,sm+=c,e[z].c-=c,e[z^1].c+=c;
if(!fl)break;
}
return sm;
}
int flow()
{
int ans=0;
while(bfs())ans+=dfs(s,inf);
return ans;
}
}D;