最大流-EK算法

最大流

给出一个图,图上的每一条边都有一个流量限制,要求每条边的实际流量都不大于流量限制,且除起点和终点外,每个点的流进量等于流出量。要求最后终点流量最大(若理解起来有点困难,可以联系一下水管系统)。


基本定理

反向弧

对于一条边,有一条反向边,这条边的流量限制是0(注意,这不是真正存在的边,所以容量=0),我们称之为反向弧。对于一条u->v的边,他的反向弧的流量是他流量的相反数。后向弧起到的作用是“撤销”,因为往后向弧加流量就等同于往真正的边减流量。

增广路

一条从s走到t的路径,(该路径中可以存在后向弧),要求走过的边的残量r需均>0


EK算法

全称Edmond-Karp算法
这个算法的样子就是不断找出增广路,而且是用最暴力的方法——直接BFS!然后就好了
时间复杂度为:O( nm2 );

模板

模板题在此:hihocoder 1369

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF=(((1<<30)-1)<<1)+1;
struct hdata{
    int dad,j;
    hdata (int dad=0,int j=0):dad(dad),j(j){}
}fa[505];
int n,e,ans,tot,lnk[505],que[505],dst[505],cap[40005],son[40005],nxt[40005],flow[40005];
bool vs[505];
void _add(int x,int y,int z){
    son[++tot]=y; cap[tot]=z; flow[tot]=0; nxt[tot]=lnk[x]; lnk[x]=tot;
    son[++tot]=x; cap[tot]=0; flow[tot]=0; nxt[tot]=lnk[y]; lnk[y]=tot;
}
inline void readi(int &x){
    x=0; char ch=getchar();
    while ('0'>ch||ch>'9') ch=getchar();
    while ('0'<=ch&&ch<='9') {x=x*10+ch-'0'; ch=getchar();}
}
int _bfs(){
    memset(vs,0,sizeof(vs)); int hed=0,til=1;
    que[1]=1; dst[1]=INF; vs[1]=1;
    while (hed!=til){
        int x=que[++hed];
        for (int j=lnk[x];j;j=nxt[j])
            if ((!vs[son[j]])&&cap[j]-flow[j]>0){
                que[++til]=son[j]; vs[son[j]]=true;
                fa[son[j]]=hdata(x,j); dst[til]=min(dst[hed],cap[j]-flow[j]);
                if (son[j]==n) return dst[til];
            }
    }
    return 0;
}
void addL(int x){
    int now=n;
    while (now!=1){
        int j=fa[now].j;
        flow[j]+=x; flow[j^1]-=x;
        now=fa[now].dad;
    }
}
int main()
{
    freopen("traffic.in","r",stdin);
    freopen("traffic.out","w",stdout);
    readi(n); readi(e); tot=1; ans=0;
    for (int i=1,x,y,z;i<=e;i++){
        readi(x); readi(y); readi(z); _add(x,y,z);
    }
    while (true){
        int tem=_bfs();
        if (!tem) break;
        addL(tem); ans+=tem;
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值