网络流最大流Edmonds-Karp算法(模板)

最大流算法的Edmonds-Karp算法,实际用的不多因为复杂度比Dinic高,把流初始化为零流,Maxflow返回最大流的值,同时在算法结束时所有已标号结点(a[u]>0的结点)构成集合S,剩余结点构成集合T,则(S,T)是图的最小割

#include<bits/stdc++.h>
using namespace std;
const int maxn=10050;
const int inf=2e9;

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

struct EdmondsKarp{
    int n,m;
    vector<Edge> edges; //边数的两倍
    vector<int> g[maxn];//邻接表,g[i][j]表示结点i的第j条边在e数组中的序号
    int a[maxn];        //当起点到i的可改进量
    int p[maxn];        //最短路树上p的入弧编号

    void init(int n){
        this->n=n;
        for(int i=0;i<n;++i) g[i].clear();
        edges.clear();
    }

    void add(int from,int to,int cap){
        edges.push_back(Edge(from,to,cap,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 Maxflow(int s,int t){
        int flow=0;
        while(1){
            memset(a,0,sizeof(a));
            queue<int> que;
            que.push(s);
            a[s]=inf;
            while(!que.empty()){
                int x=que.front();
                que.pop();
                for(int i=0;i<g[x].size();++i){
                    Edge& e=edges[g[x][i]];
                    if(!a[e.to] && e.cap>e.flow){
                        p[e.to]=g[x][i];
                        a[e.to]=min(a[x],e.cap-e.flow);
                        que.push(e.to);
                    }
                }
                if(a[t]) break;
            }
            if(!a[t]) 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;
    }
};

猜你喜欢

转载自blog.csdn.net/xiao_k666/article/details/81269217