1. 程式人生 > >網絡流最大流模板(洛谷3376)——Dinic

網絡流最大流模板(洛谷3376)——Dinic

pen crt const || div color ini 技術分享 消息

  小道消息,據說NOIP 2017 的六個題是三位(前?)國家隊大神出的,所以難度很有可能賊高,並且可能出現網絡流,所以慌慌張張地來打了個Dinic 模板,但願汝佳所說“在大多數比賽中已經完全夠用了”是對的。

技術分享
 1 #include<queue>
 2 #include<vector>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<cstring>
 6 #include<cstdlib>
 7 #include<cstdio>
 8
using namespace std; 9 const int N=100111,iNF=0x7fffffff; 10 struct edge{int from,to,cap,flow;}; 11 int n,m,sx,tx,res,crt[N],depth[N]; 12 vector<int> gr[N]; 13 vector<edge> e; 14 15 bool bfs(){ 16 bool vis[N];memset(vis,0,sizeof vis); 17 memset(depth,0,sizeof depth); 18 queue<int
> q;q.push(sx);vis[sx]=true; 19 20 while(!q.empty()){ 21 int x=q.front();q.pop(); 22 for(int i=0;i<gr[x].size();i++){ 23 edge &u=e[gr[x][i]]; 24 if(!vis[u.to]&&u.cap>u.flow){ 25 vis[u.to]=true; 26 depth[u.to]=depth[x]+1
; 27 q.push(u.to); 28 } 29 } 30 } 31 return vis[tx]; 32 } 33 34 int dfs(int x,int v){ 35 if(x==tx||v==0)return v; 36 int flow=0,f; 37 for(int &i=crt[x];i<gr[x].size();i++){ 38 edge &u=e[gr[x][i]]; 39 if(depth[u.to]==depth[x]+1&&(f=dfs(u.to,min(v,u.cap-u.flow)))>0){ 40 u.flow+=f; 41 e[gr[x][i]^1].flow-=f; 42 flow+=f; 43 v-=f; 44 45 if(v==0)break; 46 } 47 } 48 return flow; 49 } 50 51 int main(){ 52 ios::sync_with_stdio(false); 53 freopen("Dinic.in","r",stdin); 54 cin>>n>>m>>sx>>tx; 55 while(m--){ 56 int x,y,v;cin>>x>>y>>v; 57 e.push_back((edge){x,y,v,0}); 58 e.push_back((edge){y,x,0,0}); 59 gr[x].push_back(e.size()-2); 60 gr[y].push_back(e.size()-1); 61 } 62 while(bfs()){ 63 memset(crt,0,sizeof crt); 64 res+=dfs(sx,iNF); 65 } 66 cout<<res<<endl; 67 return 0; 68 }
Method_01

  洛谷 288ms

網絡流最大流模板(洛谷3376)——Dinic