Ford-Fulkerson algorithm to solve the max flow problem

本文介绍了一种经典的求解最大流问题的算法——Ford-Fulkerson算法,并提供了详细的C++实现代码。通过该算法可以有效地找出网络中从源点到汇点的最大流量。
//
//  main.cpp
//  Ford-Fulkerson
//
//  Created by Longxiang Lyu on 8/9/16.
//  Copyright (c) 2016 Longxiang Lyu. All rights reserved.
//

#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace std;


bool bfs(vector<vector<int>> &rGraph, vector<int> &parent, int s, int t)
{
    int V = rGraph.size();
    vector<int> visited(V, 0);      // mark all vertices as unvisited
    queue<int> q;
    q.push(s);
    visited[s] = 1;                 // mark source vertex as visited
    
    parent.clear();
    parent.resize(V);
    parent[s] = -1;
    
    while (!q.empty())
    {
        int u = q.front();          // get the first element
        q.pop();
        
        for (int v = 0; v != V; ++v)
        {
            if (visited[v] == 0 && rGraph[u][v] > 0)
            {
                q.push(v);
                parent[v] = u;
                visited[v] = 1;
            }
        }
    }
    return visited[t] == 1;
}

int fordFulkerson(vector<vector<int>> &graph, int s, int t)
{
    int u, v;
    
    vector<vector<int>> rGraph = graph;
    
    vector<int> parent;
    
    int max_flow = 0;               // initially zero flow
    
    while (bfs(rGraph, parent, s, t))
    {
        int bottleneck = INT_MAX;
        
        // get the bottleneck capacity of the augment path
        for (v = t; v != s; v = parent[v])
        {
            u = parent[v];
            bottleneck = min(bottleneck, rGraph[u][v]);
        }
        
        for (v = t; v != s; v = parent[v])
        {
            u = parent[v];
            rGraph[u][v] -= bottleneck;
            rGraph[v][u] += bottleneck;
        }
        
        max_flow += bottleneck;
        
    }
    
    return max_flow;
}

int main(int argc, const char * argv[])
{
    // insert code here...
    vector<vector<int>> graph = { {0, 16, 13, 0, 0, 0},
        {0, 0, 10, 12, 0, 0},
        {0, 4, 0, 0, 14, 0},
        {0, 0, 9, 0, 0, 20},
        {0, 0, 0, 7, 0, 4},
        {0, 0, 0, 0, 0, 0}
    };
    
    cout << "The maximum possible flow is " << fordFulkerson(graph, 0, 5);
    
    return 0;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值