hdu 1532 Drainage Ditches(网络流dinic模板)

题目链接:点击打开链接


网络流dinic模板

刘汝佳版

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#define inf 10000000
#define maxn 1000
using namespace std;

struct edge{
    int from,to,cap,flow;
    edge(){}
    edge(int from,int to,int cap,int flow):from(from),to(to),cap(cap),flow(flow){}
};

struct dinic{
    int n,m,s,t;
    vector<edge> edges;
    vector<int > G[maxn];
    bool vis[maxn];
    int cur[maxn];
    int d[maxn];

    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(){
        memset(vis,0,sizeof(vis));
        queue <int> Q;
        Q.push(s);
        d[s]=0;
        vis[s]=1;
        while(!Q.empty()){
            int x=Q.front();
            Q.pop();
            for(int i=0;i<G[x].size();i++){
                edge &e=edges[G[x][i]];
                if(!vis[e.to]&&e.cap>e.flow){
                    vis[e.to]=1;
                    d[e.to]=d[x]+1;
                    Q.push(e.to);
                }
            }
        }
        return vis[t];
    }
    int dfs(int x,int a){
        if(x==t||a==0) return a;
        int flow=0;
        int f;
        for(int &i=cur[x];i<G[x].size();i++){
            edge &e=edges[G[x][i]];
            if((d[e.to]==d[x]+1)&&(f=dfs(e.to,min(e.cap-e.flow,a)))>0){
                e.flow+=f;
                edges[G[x][i]^1].flow-=f;
                flow+=f;
                a-=f;
                if(a==0) break;
            }
        }
        return flow;
    }

    int maxflow(int a,int b){
        s=a;t=b;
        int flow=0;
        while(bfs()){
            memset(cur,0,sizeof(cur));
            flow+=dfs(s,inf);
        }
        return flow;
    }
};

int main(){
    int m,n;
    while(~scanf("%d%d",&m,&n)){
        dinic D;
        for(int i=1;i<=m;i++){
            int s,t,d;
            scanf("%d%d%d",&s,&t,&d);
            D.addedge(s,t,d);
        }
        int res=D.maxflow(1,n);
        printf("%d\n",res);
    }
    return 0;
}



你可能感兴趣的:(网络流,dinic)