EK求最大流

代码见下

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1010,M=10010,inf=1<<29;
int End[M<<1],Next[M<<1],Len[M<<1],Last[N];
bool v[N];
int n,m,s,t,cnt=1,incf[N],pre[N];//注意cnt从1开始 
ll maxflow=0;
queue<int> q;
void add(int x,int y,int z)//最开始的流全为0,所以正向边为z反向边为0 
{
	End[++cnt]=y,Next[cnt]=Last[x],Len[cnt]=z,Last[x]=cnt;
	End[++cnt]=x,Next[cnt]=Last[y],Len[cnt]=0,Last[y]=cnt;
}
bool bfs()
{
	while(!q.empty()) q.pop();
	memset(v,0,sizeof(v));
	q.push(s),v[s]=1;
	incf[s]=inf;//incf[x]表示当前的残存网络上从s到x的路径的最小边长度 
	while(!q.empty())
	{
		int x=q.front();
		q.pop();
		for(int i=Last[x];i;i=Next[i])
		{
			int y=End[i],l=Len[i];
			if(!Len[i]||v[y]) continue;
			//若Len[i]为0表示这条边不存在于残存网络中,所以直接跳过 
			incf[y]=min(incf[x],l);
			pre[y]=i;//记录当前残存网络中y的前驱,之后好更新 
			q.push(y),v[y]=1;
			if(y==t) return 1;
		}
	}
	return 0;
}
void update()
{
	int x=t;
	while(x!=s)
	{
		int i=pre[x];
		Len[i]-=incf[t],Len[i^1]+=incf[t];//更新残存网络 
		x=End[i^1];
	}
	maxflow+=incf[t];
}
int main()
{
	scanf("%d%d%d%d",&n,&m,&s,&t);
	for(int i=1;i<=m;i++)
	{
		int u,v,c;
		scanf("%d%d%d",&u,&v,&c);
		add(u,v,c);
	}
	while(bfs()) update();
	printf("%lld",maxflow);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值