dinic当前弧优化板子

洛谷的板题https://www.luogu.org/problemnew/show/P3376

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
 
using namespace std;
 
const int MAX = (1ll << 31) - 1;
 
long long read(){
    long long x = 0; long long zf = 1; char ch = ' ';
    while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
    if (ch == '-') zf = -1, ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;
}

const int NN=510;
const int MM=NN*NN;
struct Edge{
    int to;
    long long dis;
} edges[MM<<1];
 vector <int> con[NN];
 int cur[NN];
int edge_num=-1;
int n, m, s, t;
 
void addEdge2(int from, int to, int dis){
    edges[++edge_num].to = to;
    edges[edge_num].dis = dis;
    con[from].push_back(edge_num);
}
 
void addEdge(int from, int to, int dis){
    addEdge2(from, to, dis), addEdge2(to, from, 0);
}
 
int d[NN];
 
long long DFS(int u, long long flow){
    if (u == t) return flow;
    long long _flow = 0, __flow;
    int up=con[u].size();
    for (int i = cur[u]; i<up ; i++){
        int c_e=con[u][i];
        int v = edges[c_e].to;
        if (d[v] == d[u] + 1 && edges[c_e].dis > 0){
            __flow = DFS(v, min(flow, edges[c_e].dis));
            flow -= __flow;
            edges[c_e].dis -= __flow;
            _flow += __flow;
            edges[c_e^1].dis += __flow;
            if (!flow)
                break;
        }
    }
    if (!_flow) d[u] = -1;
    return _flow;
}
 
bool BFS(){
    memset(d, -1, sizeof(d));
    queue<int> que; que.push(s);
    d[s] = 0; int u, _new;
    while (!que.empty()){
        u = que.front(), que.pop();
        int up=con[u].size();
        for (int i = 0; i<up; i++){
            int c_e=con[u][i];
            _new = edges[c_e].to;
            if (d[_new] == -1 && edges[c_e].dis > 0){
                d[_new] = d[u] + 1;
                que.push(_new);
            }
        }
    }
    return (d[t] != -1);
}
 
long long dinic(){
    long long max_flow = 0;
    while (BFS()){
        for (int i = 1; i <= n; ++i) cur[i] = 0;
        max_flow += DFS(s, MAX);
    }
    return max_flow;
}
int main(){
    n = read(), m = read(), s = read(), t = read();//点数边数源点汇点
    for (int i = 0; i < m; i++){
        int u = read(), v = read(), w = read();//边流量
        addEdge(u, v, w);
    }
    long long ans=dinic();printf("%lld\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值