Luogu-3376 (Net maximum flow template-dinic)

topic

Topic link https://www.luogu.org/problemnew/show/P3376
network stream notes link http://blog.csdn.net/jackypigpig/article/details/78565098

program

Dinic

#include <cstdio>
#include <cstring>
#include <algorithm>
#define inf 1147473647
#define For(x) for (int h=head[x]; h; h=E[h].nxt)
#define V (E[h].v)
#define R (E[h].cap-E[h].flow)
using namespace std;
struct Edge{
   
   int v,cap,flow,nxt;} E[200005];
int head[10005],num;
int n,m,S,T,ans,dis[10005];
int q[10005],l,r;
void Add(int u,int v,int w){
    E[++num]=(Edge){v,w,0,head[u]}; head[u]=num;    //正向弧 
    E[++num]=(Edge){u,w,w,head[v]}; head[v]=num;    //反向弧 
}

void init(){
    num=1;
    //注意这里,为了保证 异或 得到反向边的正确性,num 初始只要设为奇数(使得正向边编号为偶数) 
    memset(head,0,sizeof(head));
    scanf("%d%d%d%d",&n,&m,&S,&T);
    for (int i=1,uu,vv,ww; i<=m; i++){
        scanf("%d%d%d",&uu,&vv,&ww);
        Add(uu,vv,ww);      //新建好弧 
    }
}

//分层,要是搜索不到汇点 T,则说明没有增广路了。 
bool bfs(){
    memset(dis,0,sizeof(dis));
    dis[S]=1;
    for (q[l=r=0]=S; l<=r; l++){
        For(q[l]) if (!dis[V] && R>0){      // V 还没分过层,且 u->v 还有残余流量,说明可用 
            dis[V]=dis[q[l]]+1;
            q[++r]=V;
        }
    }
    if (dis[T]) return 1;   //还有增广路 
    return 0;
}

//返回经过 x 的若干条可行增广路的流量,最大流量和到目前为止是 low 
int find(int x,int low){        
    if (x==T) return low;
    int a,tmp=0;            //tmp:经过 x 节点,最多能增加的流 
    For(x) if (dis[V]==dis[x]+1 && R>0){    //一条可行的弧 
        a=find(V,min(low-tmp,R));
        E[h].flow+=a;
        E[h^1].flow-=a;
        tmp+=a;

        if (tmp==low) return tmp;  //这两句加上能快许多。
        dis[V]=-1;

    }
    return tmp;
}

int main(){
    freopen("1.txt","r",stdin);
    init();
    while (bfs())           //分层操作 
        ans+=find(S,inf);   //找出若干增广路径时增加的流最大 
    printf("%d\n",ans);
}

prompt

  • Note that adding a current arc optimization to find can significantly improve the time.
  • If it is an undirected graph (two-way edge), just set the flow of the forward and reverse edges to 0 in the added edge. (See bzoj-1001 Wolfclaw Bunny )

Guess you like

Origin blog.csdn.net/jackypigpig/article/details/78565126