算法导论—最大流(Edmonds-Karp算法)

华电北风吹
天津大学认知计算与应用重点实验室
2016-07-20

有向图的最大流算法代码模板。利用广度优先搜索寻找残量网络增广路。

参考代码:

#include 
#include 
#include 
using namespace std;

#define maxn 10
#define INT_MIN 0x80000000

struct Edge
{
    int from, to, capacity, flow;
    Edge(int u, int v, int c, int f) :from(u), to(v), capacity(c), flow(f){}
};

struct EdmondsKarp
{
    int n, m;
    vector edges;
    vector<int> G[maxn];
    int a[maxn];
    int p[maxn];

    void Init(int n)
    {
        for (int i = 0; i < n; i++)
        {
            G[i].clear();
        }
        edges.clear();
    }

    void AddEdge(int from, int to, int capacity)
    {
        edges.push_back(Edge(from, to, capacity, 0));
        edges.push_back(Edge(to, from, 0, 0));
        m = edges.size();
        G[from].push_back(m - 2);
        G[to].push_back(m - 1);
    }

    int MaxFlowComputation(int s, int t)
    {
        int flow = 0;
        while (true)
        {
            memset(a, 0, sizeof(a));
            queue<int> Q;
            Q.push(s); 
            a[s] = INT_MIN;
            while (Q.empty()==false)
            {
                int x = Q.front();
                Q.pop();
                for (int i = 0; i < G[x].size(); i++)
                {
                    Edge & e = edges[G[x][i]];
                    if ((a[e.to] == 0) && (e.capacity>e.flow))
                    {
                        p[e.to] = G[x][i];
                        a[e.to] = min(a[x], e.capacity - e.flow);
                        Q.push(e.to);
                    }
                }
                if (a[t] > 0)
                {
                    break;
                }
            }
            if (a[t] == 0)
            {
                break;
            }
            for (int u = t; u != s; u = edges[p[u]].from)
            {
                edges[p[u]].flow += a[t];
                edges[p[u] ^ 1].flow -= a[t];
            }
            flow += a[t];
        }
        return flow;
    }
};

你可能感兴趣的:(算法导论)