最大網路流問題(PPT連結)
阿新 • • 發佈:2018-12-17
dinic(其實所有最大流的演算法都是)
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> using namespace std; struct edge{ int y,r,next,op; }a[401]; int head[201],q[5001],level[201],ans=0,x,y,z,n,m,vs,vt,tot=0; void add(int x,int y,int z){ a[++tot].y=y; a[tot].r=z; a[tot].next=head[x]; head[x]=tot; a[tot].op=tot+1; a[++tot].y=x; a[tot].r=0; a[tot].next=head[y]; head[y]=tot; a[tot].op=tot-1; } bool bfs(){ int u,tmp,v,f=1,r=1; memset(level,0,sizeof(level)); q[f]=vs; level[vs]=1; while(f<=r){ v=q[f]; tmp=head[v]; while(tmp!=-1){ u=a[tmp].y; if(a[tmp].r&&!level[u]){ level[u]=level[v]+1; q[++r]=u; if(u==vt)return true; } tmp=a[tmp].next; } f++; } return false; } int dfs(int v,int num){ int value,flow,tmp,u,ans=0; if(v==vt||!num)return num; tmp=head[v]; while(tmp!=-1){ u=a[tmp].y; value=a[tmp].r; if(level[u]==level[v]+1){ flow=dfs(u,min(value,num)); if(flow){ a[tmp].r-=flow; a[a[tmp].op].r+=flow; ans+=flow; num-=flow; if(!num)break; } } tmp=a[tmp].next; } return ans; } int main(){ scanf("%d%d",&n,&m); vs=1; vt=m; memset(head,255,sizeof(head)); for(int i=1;i<=n;i++){ scanf("%d%d%d",&x,&y,&z); add(x,y,z); } while(bfs()){ ans+=dfs(1,2147483647); } printf("%d",ans); return 0; }