Maximum Flow of Network - the largest network flow template

Topic Link

Meaning of the questions:

FIG gives a network, and the source and sink, the network obtains its maximum flow.

answer:

Seeking maximum flow network flow template

Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxm=1e7+5;
const int maxn=1e6+5;
int n,m,k;
struct node{
    ll t,cap,flow,next;    //cap容量,flow流量
}e[maxm];
int head[maxn],cur[maxn],cnt; //cur优化dfs中的head
void add(int u,int v,int cap)   //u-> v capacity CAP 
{ 

    E [CNT] = Node {V, CAP, 0 , head [U]}; 
    head [U] = CNT ++ ; 
    E [CNT] = Node {U, 0 , 0 , head [V ]}; // capacity of the reverse side 0 
    head [V] = CNT ++ ; 
} 
int DEP [MAXN];     // BFS depth 
BOOL BFS ( int S, int T)    // O (n-m +) 
{ 
    Memset ( DEP, 0 , the sizeof (DEP)); 
    Queue < int > Q; 
    q.push (S); 
    DEP [S] =1;
    while(!q.empty())
    {
        int u=q.front();q.pop();
        for(int i=head[u];~i;i=e[i].next)
        {
            int v=e[i].t;
            if(dep[v]==0&&e[i].cap-e[i].flow>0)
            {
                dep[v]=dep[u]+1;
                q.push(v);
            }
        }
    }
    return dep[t]>0;     //存在增广路
}
ll dfs(ints, int T, LL minedge) 
{ 
    IF (s == T) return minedge; 
    LL Flow = 0 ;     // from the current point s effluent flow rate 
    for ( int & CUR = I [s]; ~ I; I = E [ I] .next) 
    { 
        int V = E [I] .T;
         IF (DEP [V] == DEP [S] + . 1 && E [I] .cap-E [I] .flow> 0 )    // hierarchy && a surplus flow 
        { 
            LL TEMP = DFS (V, T, min (minedge-flow, E [I] .cap- E [I] .flow)); 
            E [I] .flow + = TEMP;     // increase traffic 
            e [i ^. 1 ] .flow- = TEMP;     // reverse side flow reduction 
            Flow + = TEMP;     // Flow assigned traffic 
            IF (Flow == minedge) return Flow;   // has reached the maximum flow ancestors, no longer a large, cut branch 
        } 
    } 
    IF (flow == 0 ) DEP [S] = 0 ;    // at this point no longer flow, mark off 
    return flow; 
} 
LL Dinic ( int S, int T)    // must establish a reverse side cap = 0 
{ 
    LL MaxFlow = 0 ;
     the while (BFS (S, T))    // there augmenting path 
    { 
        memcpy (cur, head,sizeof(head));   //重要的优化
        maxflow+=dfs(s,t,inf);
    }
    return maxflow;
}
void init()
{
    memset(head,-1,sizeof head);
    cnt=0;
}
int main()
{
    int n,m,s,t;
    scanf("%d%d%d%d",&n,&m,&s,&t);
    init();
    for(int i=1; i<=m; i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        add(u,v,w);
    }
    int ans=dinic(s,t);
    printf("%d\n",ans);
    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/j666/p/11704165.html