Luogu-3376 (网最大流模板-dinic)

来源:互联网 发布:携程 去哪儿知乎 编辑:程序博客网 时间:2024/06/06 20:36

题目

题目链接 https://www.luogu.org/problemnew/show/P3376
网络流笔记链接 http://blog.csdn.net/jackypigpig/article/details/78565098

程序

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);}

提示

  • 注意在 find 那里加上个当前弧优化可以显著提升时间。
  • 要是是无向图(双向边)的话,只需在加边那里把正向、反向边的 flow 都设成 0 即可。(参见 bzoj-1001 狼爪兔子 )
原创粉丝点击