Network flow algorithm for maximum flow --Dinic

Dinic worst time complexity of O (n * n * m) The average O (n).

Algorithm idea: build a hierarchy view of BFS, if the sink is not the end of the hierarchical graph algorithm returns the maximum flow, or DFS found in all hierarchical graph in Figure augmenting path, augmented after the end of the re-establishment of hierarchical graph.

 

Optimization: Multiple augmented optimization: the traffic to all nodes of augmenting paths recorded directly returned.

   Fried point optimization: If no change point traffic directly discarded.

 

code:

#include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <stack>
#define FT(a, b) memset(a, b, sizeof(a))
#define FAT(a) memset(a, 0, sizeof(a))
using namespace std;
typedef long long ll;
M = 2e5 +intconst 10;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int n, m, s, t;
int h[M], e[M], ne[M], w[M], idx;
int deepth[M];
void add(int a, int b, int c)
{
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
bool bfs()// bfs求深度
{
    FT(deepth, -1);
    queue<int> q;
    q.push (S); 
    deepth [S] = 0 ;
     the while (! q.empty ()) 
    { 
        int A = q.front (); 
        q.pop (); 
        for ( int I = H [A]; ~ I; I = NE [I]) 
        { 
            int J = E [I];
             IF (W [I] && deepth [J] == - . 1 ) // only not been accessed and there is flow 
            { 
                deepth [J] deepth = [A] + . 1 ; 
                q.push (J); 
            } 
        } 
    } 
    return deepth [T] = -!. 1 ; 
} 
int DFS ( int now, int Flow) 
{ 
    IF (now == T)
         return Flow;
     int nowflow = 0 ; // multiple augmented optimization 
    for ( int I = H [now]; ~ I; I = NE [I]) 
    { 
        int J = E [I];
         IF (W [I] && deepth [J] == deepth [now] + . 1 ) // must flow and a point deep than 
        {
             int K = DFS (J, min (Flow, W [I])); 
            W [I] - = K;
            w[i ^ 1] += k;
            flow -= k;
            nowflow += k;
        }
    }
    if (!nowflow)
        deepth[now] = -2; //炸点优化
    return nowflow;
}
int dinic()
{
    int ans = 0;
    while (bfs())
        ans += dfs(s, INF);
    return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("D://code//c++//in.txt", "r", stdin);
#endif
    scanf("%d%d%d%d", &n, &m, &s, &t);
    FT(h, -1);
    idx = 0;
    for (int i = 0; i < m; i++)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c), add(b, a, 0);
    }
    printf("%d\n", dinic());

    return 0;
}

 

Guess you like

Origin www.cnblogs.com/ignorance/p/12576462.html