最大流dinic 模版 (训练指南)

struct Edge
{
    int from,to,cap,flow;
};

struct Dinic
{
    int n,m,s,t;
    vector<Edge> edges;
    vector<int> G[maxn];
    bool vis[maxn];
    int d[maxn];
    int cur[maxn];
    void init(int n)
    {
        REP(i,1,n) G[i].clear();
        edges.clear();
    }
    void addedge(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);
    }
    bool bfs()
    {
        MS0(vis);
        queue<int> q;
        q.push(s);
        d[s]=0;
        vis[s]=1;
        while(!q.empty()){
            int u=q.front();q.pop();
            for(int i=0;i<G[u].size();i++){
                Edge& e=edges[G[u][i]];
                if(!vis[e.to]&&e.cap>e.flow){
                    vis[e.to]=1;
                    d[e.to]=d[u]+1;
                    q.push(e.to);
                }
            }
        }
        return vis[t];
    }
    int dfs(int u,int a)
    {
        if(u==t||a==0) return a;
        int flow=0,f;
        for(int& i=cur[u];i<G[u].size();i++){
            Edge& e=edges[G[u][i]];
            if(d[u]+1==d[e.to]&&(f=dfs(e.to,min(a,e.cap-e.flow)))>0){
                e.flow+=f;
                edges[G[u][i]^1].flow-=f;
                flow+=f;
                a-=f;
                if(a==0) break;
            }
        }
        return flow;
    }
    int Maxflow(int s,int t)
    {
        this->s=s;this->t=t;
        int flow=0;
        while(bfs()){
            MS0(cur);
            flow+=dfs(s,INF);
        }
        return flow;
    }
};Dinic F;
View Code

 

你可能感兴趣的:(最大流dinic 模版 (训练指南))