网络流 最大流(dinic邻接表) 手敲模板

SAP + GAP 邻接表:https://blog.csdn.net/Adolphrocs/article/details/84779575

SAP + GAP 邻接矩阵:https://blog.csdn.net/Adolphrocs/article/details/84779661

dinic 邻接矩阵:https://blog.csdn.net/Adolphrocs/article/details/84779732

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=205;
const int maxx=200005;
int edge;
int to[maxx], flow[maxx], nex[maxx];
int head[maxn];
int n, np, nc, m;
void addEdge(int v, int u, int cap){
    to[edge] = u, flow[edge] = cap, nex[edge] = head[v], head[v] = edge++;
    to[edge] = v, flow[edge] = 0, nex[edge] = head[u], head[u] = edge++;
}
int vis[maxn];
int pre[maxn];
bool bfs(int s,int e) {
    queue<int> que;
    pre[s] = -1;
    memset(vis, -1, sizeof(vis));
    que.push(s);
    vis[s] = 0;
    while(!que.empty()) {
        int u = que.front();
        que.pop();
        for(int i = head[u]; ~i; i = nex[i]) {
            int v = to[i];
            if(vis[v] == -1 && flow[i]) {
                vis[v] = vis[u] + 1;
                if(v == e)
                    return true;
                que.push(v);
            }
        }
    }
    return false;
}
int dfs(int s, int t, int f){
    if(s == t || !f)
        return f;
    int r = 0;
    for(int i = head[s]; ~i; i = nex[i]) {
        int v = to[i];
        if(vis[v] == vis[s] + 1 && flow[i]) {
            int d = dfs(v, t, min(f, flow[i]));
            if(d > 0) {
                flow[i] -= d;
                flow[i ^ 1] += d;
                r += d;
                f -= d;
                if(!f)
                    break;
            }
        }
    }
    if(!r)
        vis[s] = INF;
    return r;
}

int maxFlow(int s, int e) {//然后直接调用这个即可
    int ans = 0;
    while(bfs(s, e))
        ans += dfs(s, e, INF);
    return ans;
}

void init() {//记得每次使用前初始化
    memset(head, -1, sizeof(head));
    edge = 0;
}

int main() {
    while(~scanf("%d%d%d%d", &n, &np, &nc, &m)) {//n作为源点,n+1作为汇点
        init();
        int ai, bi, ci;
        for(int i = 0; i < m; i++) { //ai到bi最大传输量为ci
            while(getchar() != '(');
            scanf("%d%*c%d%*c%d", &ai, &bi, &ci);
            addEdge(ai, bi, ci);
        }
        for(int i = 0; i < np; i++) {//ai最大发电量为bi
            while(getchar() != '(');
            scanf("%d%*c%d", &ai, &bi);
            addEdge(n, ai, bi);
        }
        for(int i = 0; i < nc; i++) {//ai最大消耗量为bi
            while(getchar() != '(');
            scanf("%d%*c%d", &ai, &bi);
            addEdge(ai, n + 1, bi);
        }
        printf("%d\n", maxFlow(n, n + 1));
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值