Just engage in a practice of it.
https://www.luogu.org/problem/P3376 network flow maximum flow board.
Program large part of the reference from A_Comme_Amour solution to a problem greatly.
Dinic:
1. running from stratified s bfs again, if assigned t layer, go to 2.
2. Run dfs, find the current flow, added to the answer. For details please go to 3.
3.dfs (u, t, lim) represents the (current point, sink, the minimum arc path), at first to judge two cases: (1 to the sink, i.e. the minimum arc u == t 2. 0 that lim == 0, can be directly return lim)
Then run dfs: which direction to go? (To stratification at that point the new point +1 depth is old and can go (f = dfs (v, t, min (lim, w)), that is, to find augmenting paths), this time the update path: the same route -f, reverse + f, flow + f, lim-f, lim determine if it is less than or equal to 0 will not need to gain wide down the last return flow.
4. Finally, the return flow and the like.
The arc may be selected to optimize, little details, see the specific procedures:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 const int inf=1e9; 7 const int N=1e6+10; 8 int n,m,S,T,cnt=-1,maxflow,head[N],cur[N],deep[N]; 9 queue<int> q; 10 struct edge{ 11 int to,next,w; 12 }e[N*2]; 13 void addedge(int from,int to,int w){ 14 e[++cnt]=(edge){to,head[from],w}; 15 head[from]=cnt; 16 } 17 int bfs(int s,int t){//将图分层。 18 for(int i=1;i<=n;i++) deep[i]=1e9+10; 19 while(!q.empty()) q.pop(); 20 for(int i=1;i<=n;i++) cur[i]=head[i]; 21 deep[s]=0; 22 q.push(s); 23 while(!q.empty()){ 24 int u=q.front(); 25 q.pop(); 26 for(int i=head[u];i!=-1;i=e[i].next){ 27 int v=e[i].to; 28 if(deep[v]>inf&&e[i].w){ 29 deep[v]=deep[u]+1; 30 q.push(v); 31 } 32 } 33 } 34 is IF (Deep [T] <INF) return to true ; 35 the else return to false ; 36 } 37 [ int DFS ( int U, int T, int Lim) { // Lim = minedge (S-> U) 38 is IF (! T || U == Lim) return Lim; // if the sink or to the right side to the right side of 0 is returned. 39 int Flow = 0 , F; 40 for ( int I = CUR [U]; I = -! . 1 ; I = E [I] .next) { 41 is CUR [U] = I; //Optimization of the arc 42 is int V = E [I] .to; 43 is IF (Deep [V] == Deep [U] + . 1 && (DFS = F (V, T, min (Lim, E [I] .W)) )) { // if this can reach the sink and subject to delamination 44 is Flow + = F; 45 lim- = F; 46 is E [I] .w- = F; 47 E [I ^ . 1 ] .W + = F; 48 IF (Lim!) BREAK ; 49 } 50 } 51 is return Flow; 52 is } // Important 53 is void Dinic (int s,int t){ 54 while(bfs(s,t)){ 55 maxflow+=dfs(s,t,inf); 56 } 57 } 58 int main(){ 59 scanf("%d%d%d%d",&n,&m,&S,&T); 60 int x,y,z; 61 memset(head,-1,sizeof(head)); 62 for(int i=1;i<=m;i++){ 63 scanf("%d%d%d",&x,&y,&z); 64 addedge(x,y,z); 65 addedge(y,x,0); 66 } 67 dinic(S,T); 68 printf("%d",maxflow); 69 return 0; 70 }
Originally want to engage ISAP, but lazy, pigeon with it.