Hdu3549 Flow Problem(网络流)

链接:点击跳转
网络流模板题
代码如下:

#include<bits/stdc++.h>

using namespace std;
typedef unsigned long long ll;
const int MAXN = 2e3 + 5;
const int INF = 0x3f3f3f3f;
#define endl '\n'

inline void IO_STREAM() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
}

struct Edge{
    int to,val,nxt;
}e[MAXN];

int head[MAXN], deep[MAXN];
int n, m, s, t, cnt;
ll res;

inline void init() {
    for (int i = 1; i <= n; i++) head[i] = -1;
    cnt = 0;
}

inline void add(int from, int to, int val) {
    e[cnt] = Edge{to, val, head[from]};
    head[from] = cnt++;
}

inline int bfs() { 
    for (int i = 2; i <= t; i++) deep[i] = -1;
    queue<int>q;
    deep[s] = 1;
    q.push(s);
    while (!q.empty()) {
        int front = q.front();
        q.pop();
        for (int i = head[front]; i != -1; i = e[i].nxt) {
            if (deep[e[i].to] == -1 && e[i].val) {
                deep[e[i].to] = deep[front] + 1;
                q.push(e[i].to);
            }
        }
    }
    return  (deep[t] != -1);
}

inline int dfs(int x, int totFlow) {
    if (x == t || totFlow ==0) return totFlow;
    int ans = totFlow;
    for (int i = head[x]; i != -1; i = e[i].nxt) {
        if (deep[e[i].to] == deep[x] + 1 && e[i].val) {
            int flow = dfs(e[i].to, min(totFlow,e[i].val));
            e[i].val -= flow;
            e[i ^ 1].val += flow;
            totFlow -= flow;
            if (totFlow == 0) return ans;
        }
    }
    return ans - totFlow;
}

inline void dinic() {
    while (bfs()) {
        res += dfs(s, INF);
    }
}

int main() {
    IO_STREAM();
    int Case;
    int ans = 1;
    cin >> Case;
    while (Case--) {
        cin >> n >> m;
        s = 1, t = n;
        init();
        for (int i = 0; i < m; i++) {
            int x, y, c;
            cin >> x >> y >> c;
            add(x, y, c);
            add(y, x, 0);//建反边
        }
        res = 0;
        dinic();
        cout << "Case " << ans++ << ": " << res << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值