Edmonds-Karp

Maximum Flow

A Edmonds-Karp

Code

t i m e : O ( V ∗ E 2 ) time: O(V*E^2) time:O(VE2)

/*
 * @Descripttion: Edmonds-Karp
 * @version: 1.0
 * @Author: pineklll
 * @Date: 2022-03-24 13:56:09
 * @LastEditors: pineklll
 * @LastEditTime: 2022-03-24 14:28:00
 */
#include <bits\stdc++.h>

const int INF = 1e9;
const int maxn = 300;
int n, m, 
    // the graph and the residual graph all together
    graph[maxn][maxn], 
    // if we have visited the vec, in the meantime record the path
    pre[maxn];

/**
 * @brief BFS(not efficient using DFS)
 * 
 * @param s source point 
 * @param t target point
 * @return int the maximum capacity along the path
 */
int bfs(int s, int t){
    int flow[maxn];
    memset(pre, -1, sizeof pre);
    // cause we wanna take the minimum value
    flow[s] = INF;
    pre[s] = 0;
    std::queue<int> Q;
    Q.push(s);
    while(!Q.empty()){
        int fr = Q.front();
        Q.pop();
        // until we reach the end
        if(fr==t)
            break;
        for (int i = 1; i <= m; i++){
            // not the source point, left some flow, and haven't visited yet
            if (i != s && graph[fr][i] > 0 && pre[i] == -1){
                pre[i] = fr;
                Q.push(i);
                // record the maximum flow on the path
                flow[i] = std::min(flow[fr], graph[fr][i]);
            }
        }
    }
    if(pre[t]==-1)
        return -1;
    return flow[t];
}

/**
 * @brief figure out the MaxFlow --- O(V*E^2)
 * 
 * @param s source point
 * @param t target point
 * @return int maxflow
 */
int maxflow(int s, int t){
    int Maxflow = 0;
    while(1){
        int flow = bfs(s, t);
        if (flow == -1)
            break;
        // update the graph
        int cur = t;
        while (cur != s){
            int father = pre[cur];
            // for residual graph
            graph[father][cur] -= flow;
            graph[cur][father] += flow;
            cur = father;
        }
        Maxflow += flow;
    }
    return Maxflow;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值