网络流-最大流 dinic+当前弧优化(模板)
生活随笔
收集整理的這篇文章主要介紹了
网络流-最大流 dinic+当前弧优化(模板)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用法:在原有向圖的基礎上,增加源點s和匯點t,并將s與左子集建邊,t與右子集建邊:
模板代碼:
const int N=210;struct Edge {int to,w,next; }edge[N*N];//邊數int head[N],cnt;void addedge(int u,int v,int w) {edge[cnt].to=v;edge[cnt].w=w;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;//反向邊邊權設置為0edge[cnt].next=head[v];head[v]=cnt++; }int d[N],now[N];//深度 當前弧優化bool bfs(int s,int t)//尋找增廣路 {memset(d,0,sizeof(d));queue<int>q;q.push(s);now[s]=head[s];d[s]=1;while(!q.empty()){int u=q.front();q.pop();for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(d[v])continue;if(!w)continue;d[v]=d[u]+1;now[v]=head[v];q.push(v);if(v==t)return true;}}return false; }int dinic(int x,int t,int flow)//更新答案 {if(x==t)return flow;int rest=flow,i;for(i=now[x];i!=-1&&rest;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;if(w&&d[v]==d[x]+1){int k=dinic(v,t,min(rest,w));if(!k)d[v]=0;edge[i].w-=k;edge[i^1].w+=k;rest-=k;}}now[x]=i;return flow-rest; }void init() {memset(now,0,sizeof(now));memset(head,-1,sizeof(head));cnt=0; }int solve(int st,int ed) {int ans=0,flow;while(bfs(st,ed))while(flow=dinic(st,ed,inf))ans+=flow;return ans; }封裝后的模板:
template<typename T> struct Dinic {const static int N=410;const static int M=N*N;const T inf=0x3f3f3f3f3f3f3f3f;struct Edge{int to,next;T w;}edge[M];//邊數int head[N],cnt;void addedge(int u,int v,T w){edge[cnt].to=v;edge[cnt].w=w;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;//反向邊邊權設置為0edge[cnt].next=head[v];head[v]=cnt++;}int d[N],now[N];//深度 當前弧優化bool bfs(int s,int t)//尋找增廣路{memset(d,0,sizeof(d));queue<int>q;q.push(s);now[s]=head[s];d[s]=1;while(!q.empty()){int u=q.front();q.pop();for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;T w=edge[i].w;if(d[v])continue;if(!w)continue;d[v]=d[u]+1;now[v]=head[v];q.push(v);if(v==t)return true;}}return false;}T dinic(int x,int t,T flow)//更新答案{if(x==t)return flow;T rest=flow,i;for(i=now[x];i!=-1&&rest;i=edge[i].next){int v=edge[i].to;T w=edge[i].w;if(w&&d[v]==d[x]+1){T k=dinic(v,t,min(rest,w));if(!k)d[v]=0;edge[i].w-=k;edge[i^1].w+=k;rest-=k;}}now[x]=i;return flow-rest;}void init(){memset(now,0,sizeof(now));memset(head,-1,sizeof(head));cnt=0;}T solve(int st,int ed){T ans=0,flow;while(bfs(st,ed))while(flow=dinic(st,ed,inf))ans+=flow;return ans;} };?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的网络流-最大流 dinic+当前弧优化(模板)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ - 3614 Sunscreen
- 下一篇: POJ - 3422 Kaka's Ma