EK算法邻接表实现

#include<cstring>
#include<queue>
#include<cstdio>
#include<iostream>
#define ll long long
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e4 + 1;
const int maxm = 2*1e5 + 10;

int h[maxn], p;
int pre[maxn], pr[maxn], flow[maxn];

int n, m, s, t;
ll ans;
struct edge {
	int nes, to, w;
	
}e[maxn];

inline void add(int u, int v, int l) {
	e[p].nes = h[u], e[p].to = v, e[p].w  = l, h[u] = p++;
	
	e[p].nes = h[v], e[p].to = u, e[p].w  = 0, h[v] = p++;
}

int bfs(int s, int t) {
	queue<int> q;
	memset(pre, -1, sizeof(pre));
	flow[s] = inf;
	pre[s] = 0;
	q.push(s);
	while(!q.empty()) {
		int u = q.front(); q.pop();
		if(u == t) break;
		for(int i = h[u]; i != -1; i = e[i].nes) {
			int v = e[i].to;
			if(pre[v] == -1 && e[i].w > 0) { //有容量 并且没有访问过 
				flow[v] = min(flow[u], e[i].w); //优化最低增广 
				pre[v] = u; //记录路径 
				pr[v] = i; // u -> v 边的编号  //记录路径上用到的边的编号 
				q.push(v);
			}
		}
	}
	if(pre[t] != -1) return flow[t];
	else return -1;
}

ll EK() {
	ll tot = 0, dalte;
	while(1) { //一直寻找增广路,知道找不到为止 
		ll dalte = bfs(s, t);
		if(dalte == -1) break;
		tot += dalte; //优化最大流 
		int q = t;
		while(q != s) {
			e[pr[q]].w -= dalte;    //更新残余网络 容量网络 - 流量网络 = 残余量 
			e[pr[q]^1].w += dalte; //  跟新方向边 
			q = pre[q]; 
		}
	}
	return tot;
}

int main() {
	memset(h, -1, sizeof(h));
	ios::sync_with_stdio(false); // 关闭同步 
	cin >>n>>m>>s>>t;
	for(int i = 0; i < m; i++) {
		int u,v,l;
		cin>>u>>v>>l;
		add(u,v,l);
	}
	cout<<EK();	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值