First acquaintance with maximum flow

Dinic algorithm:

while (capable of layering)

{

  layered;

  dfs augmentation;

}

Layering: that is, the source point is layer 0, the point that can be reached in one step is the first layer, and the point that can be reached in two steps is the second layer... (an edge capacity of 0 means unreachable).

dfs augmentation: Search for a feasible flow from the source point to the sink according to the level, subtract the feasible flow to obtain the residual network, then backtrack, and then search for the feasible flow on the residual network, until backtracking to layer 0, no feasible flow can be found.

const  int MAX_N = 100 ;  
 const  int MAX_M = 10000 ;  
 const  int INF = 1000000000 ;  
 struct edge {
     int v, c, next;   // v is the right endpoint, c is the capacity 
} e[MAX_M];
 int p[MAX_N], eid;
 void init() {
    memset(p, -1, sizeof(p));
    eid = 0;
}
void insert(int u, int v, int c) {  
    e [eid] .v = v;
    e[eid].c = c;
    e[eid].next = p[u];
    p[u] = eid++ ;
}
void addedge(int u, int v, int c) {  
    insert(u, v, c);
    insert(v, u, 0);  
}
int S, T;  
int d[MAX_N];  
bool CountLayer() {  //分层 
    memset(d, -1, sizeof(d));
    queue<int> q;
    q.push(S);
    d[S] = 0;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = p[u]; i != -1; i = e[i].next) {
            int v = e[i].v;
            if (e[i].c > 0 && d[v] == -1) {
                q.push(v);
                d[v] = d[u] + 1;
            }
        }
    }
    return (d[T] != - 1 ); // Whether the source point can reach the sink point, that is, whether the layering is successful 
}

int dfs( int u, int flow) {   // flow is the maximum flow of feasible flow flowing into point u in the previous level, and the source point is positive infinity 
    if (u == T) {
         return flow;
    }
    int res = 0;
    for (int i = p[u]; i != -1; i = e[i].next) {
        int v = e[i].v;
        if (e[i].c > 0 && d[u] + 1 == d[v]) {
            int tmp = dfs(v, min(flow, e[i].c));  
            flow -= tmp;
            e[i].c -= tmp;
            res += tmp;
            e[i ^ 1].c += tmp;  
            if (flow == 0) {  
                break;
            }
        }
    }
    if (res == 0 ) {   // The feasible flow cannot be searched from this point, the flag is -1 
        d[u] = - 1 ;
    }
    return res;
}

int maxflow() {  
    int res = 0;
    while (CountLayer()) {
        res += dfs(S, INF);  
    }
    return res;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325098189&siteId=291194637