[codevs1993]草地排水(最大流)

题目描述

传送门

题解

网络流最大流模板题

代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int max_n=2005;
const int max_m=2005;
const int max_e=max_m*2;
const int inf=1e9;

int point[max_n],next[max_e],v[max_e],remain[max_e],tot;
int cur[max_n],deep[max_n],last[max_n],num[max_n];
int n,m,x,y,cap,maxflow;
queue <int> q;

inline void add(int x,int y,int cap){
    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap;
    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0;
}

inline void bfs(int t){
    for (int i=1;i<=n;++i)
      deep[i]=n;
    deep[t]=0;
    while (!q.empty()) q.pop();
    q.push(t);

    while (!q.empty()){
        int now=q.front(); q.pop();
        for (int i=point[now];i!=-1;i=next[i])
          if (deep[v[i]]==n&&remain[i^1]){
            deep[v[i]]=deep[now]+1;
            q.push(v[i]);
          }
    }
}

inline int addflow(int s, int t) {
    int ans=inf,now=t;
    while (now!=s) {
        ans=min(ans, remain[last[now]]);
        now=v[last[now] ^ 1];
    }
    now=t;
    while (now != s) {
        remain[last[now]]-=ans;
        remain[last[now]^1]+=ans;
        now=v[last[now]^1];
    }
    return ans;
}

inline void isap(int s,int t){
    int now=s;
    bfs(t);
    for (int i=1;i<=n;++i) ++num[deep[i]];
    for (int i=1;i<=n;++i) cur[i]=point[i];

    while (deep[s]<n){ 
        if (now==t){
            maxflow+=addflow(s,t);
            now=s;
        }

        bool has_find=false;
        for (int i=cur[now];i!=-1;i=next[i]){
            int u=v[i];
            if (deep[u]+1==deep[now]&&remain[i]){
                has_find=true;
                cur[now]=i;
                last[u]=i;
                now=u;
                break;
            }
        }

        if (!has_find){
            int minn=n-1;
            for (int i=point[now];i!=-1;i=next[i])
              if (remain[i])
                minn=min(minn,deep[v[i]]);
            if (!(--num[deep[now]])) break;
            num[deep[now]=minn+1]++;
            cur[now]=point[now];
            if (now!=s)
              now=v[last[now]^1];
        }
    }
}

int main(){
    tot=-1;
    memset(point,-1,sizeof(point));
    memset(next,-1,sizeof(next));

    scanf("%d%d",&m,&n);
    for (int i=1;i<=m;++i){
        scanf("%d%d%d",&x,&y,&cap);
        add(x,y,cap);
    }

    isap(1,n);
    printf("%d\n",maxflow);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值