关闭

HDU 1532 Drainage Ditches 网络流 模板题

338人阅读 评论(0) 收藏 举报
分类:

网络流 模板题

重新写了一个,更新一下模板。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 205;
const int MAXM = MAXN * MAXN;
const int INF = 0x7ffffff;

struct dinic_{
    int que[MAXN], ft, tl, tp;
    int s, t, cnt, n, m;
    int cur[MAXN], d[MAXN], head[MAXN];
    bool vis[MAXN];
    struct edge_{
        int s, t, c, f, next;
    }edge[MAXM];

    void init(){
        memset(edge, -1, sizeof(edge));
        memset(head, -1, sizeof(head));
        cnt = 0;
    }

    int add(int s, int t, int c){
        edge[cnt] = (edge_){s, t, c, 0, head[s]};
        head[s] = cnt++;
        edge[cnt] = (edge_){t, s, 0, 0, head[t]};
        head[t] = cnt++;
    }

    int bfs(){
        memset(d, 0, sizeof(d));
        memset(vis, false, sizeof(vis));
        ft = 1, tl = 0;
        que[0] = s, vis[s] = true;
        while(tl < ft){
            tp = que[tl++];
            for(int now = head[tp]; ~now; now = edge[now].next){
                edge_ &e = edge[now];
                if(!vis[e.t] && e.c > e.f){
                    d[e.t] = d[tp] + 1;
                    vis[e.t] = true;
                    que[ft++] = e.t;
                }
            }
        }
        return vis[t];
    }

    int dfs(int x, int a){
        if(x == t || a == 0)
            return a;
        int flow = 0, f;
        for(int &now = cur[x]; ~now; now = edge[now].next){
            edge_ &e = edge[now];
            if(d[e.t] == d[x] + 1 && (f = dfs(e.t, min(a, e.c - e.f))) > 0){
                    e.f += f, edge[now ^ 1].f -= f;
                    flow += f, a -= f;
                    if(a == 0)
                        break;
            }
        }
        return flow;
    }

    int maxFlow(int _s, int _t, int _n){
        int flow = 0;
        s = _s, t = _t, n = _n;
        while(bfs()){
            for(int i = 1; i <= n; ++i)
                cur[i] = head[i];
            flow += dfs(s, INF);
        }
        return flow;
    }
}dinic;

int main(){
    int n, m, s, t, c;
    while(~scanf("%d%d", &m, &n)){
        dinic.init();
        for(int i = 0; i < m; ++i){
            scanf("%d%d%d", &s, &t, &c);
            dinic.add(s, t, c);
        }
        printf("%d\n", dinic.maxFlow(1, n, n));
    }
    return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:29393次
    • 积分:919
    • 等级:
    • 排名:千里之外
    • 原创:65篇
    • 转载:2篇
    • 译文:0篇
    • 评论:4条
    最新评论