AcWing 2171:EK求最大流

85 篇文章 3 订阅
3 篇文章 0 订阅

【题目来源】
https://www.acwing.com/problem/content/description/2173/

【问题描述】
给定一个包含 n 个点 m 条边的有向图,并给定每条边的容量,边的容量非负。
图中可能存在重边和自环。求从点 S 到点 T 的最大流。


【输入格式】
第一行包含四个整数 n,m,S,T。
接下来 m 行,每行三个整数 u,v,c,表示从点 u 到点 v 存在一条有向边,容量为 c。
点的编号从 1 到 n。


【输出格式】
输出点 S 到点 T 的最大流。
如果从点 S 无法到达点 T 则输出 0。


【数据范围】
2≤n≤1000,
1≤m≤10000,
0≤c≤10000,
S≠T

【算法分析】
一、链式前向星
由于网络流是有向有权图,因此可以选择链式前向星存图。关于链式前向星的知识点,可详见:

https://blog.csdn.net/hnjzsyjyj/article/details/139369904
https://blog.csdn.net/hnjzsyjyj/article/details/126474608
https://blog.csdn.net/hnjzsyjyj/article/details/119917795
https://blog.csdn.net/hnjzsyjyj/article/details/126488154

二、异或^运算
首先给出如下的异或^运算的实例。
0^1=1, 1^1=0
2^1=3, 3^1=2
4^1=5,5^1=4
  …… 

通过观察,可知
x^1^1=x,即对一个数连续执行两次“^1”运算后,便会得到自身。这恰好与网络流中“反向边的反向边等于自身”不谋而合。
因此,在网络流的算法实现中,我们可以利用“^1”运算来表示反向边。

【算法代码】

/* 链式前向星存图
val[idx]:存储序号为 idx 的边的值
e[idx]:存储序号为 idx 的结点的编号
ne[idx]:存储序号为 idx 的结点指向的结点的编号
h[a]:存储头结点 a 指向的结点的编号
*/

#include <bits/stdc++.h>
using namespace std;

const int maxn=1010;
const int maxm=20010;
const int inf=0x3f3f3f3f;

int n,m,s,t;
int e[maxm],ne[maxm],h[maxn],val[maxm],idx;
int q[maxn],d[maxn],pre[maxm];
bool st[maxn]; //stamp

void add(int u, int v, int w) { //Construct residual network
    val[idx]=w,e[idx]=v,ne[idx]=h[u],h[u]=idx++;
    val[idx]=0,e[idx]=u,ne[idx]=h[v],h[v]=idx++;
}

bool bfs() { //Finding the Augmenting Path
    memset(st,0,sizeof st);
    int head=0;
    int tail=0;
    q[0]=s, st[s]=true, d[s]=inf;

    while(head<=tail) {
        int u=q[head++];
        for(int i=h[u]; i!=-1; i=ne[i]) {
            int j=e[i];
            if(!st[j] && val[i]) {
                st[j]=true;
                pre[j]=i;
                d[j]=min(d[u],val[i]);
                if(j==t)return true;
                q[++tail]=j;
            }
        }
    }
    return false;
}

int EK() {
    int ans=0;
    while(bfs()) {
        ans+=d[t];
        for(int i=t; i!=s; i=e[pre[i]^1]) {
            val[pre[i]]-=d[t];
            val[pre[i]^1]+=d[t];
        }
    }
    return ans;
}

int main() {
    scanf("%d%d%d%d",&n,&m,&s,&t);
    memset(h,-1,sizeof h);
    while(m--) {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        add(u,v,w);
    }

    printf("%d\n",EK());

    return 0;
}


/*
in:
7 14 1 7
1 2 5
1 3 6
1 4 5
2 3 2
2 5 3
3 2 2
3 4 3
3 5 3
3 6 7
4 6 5
5 6 1
6 5 1
5 7 8
6 7 7

out:
14
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/139369904
https://blog.csdn.net/hnjzsyjyj/article/details/126474608
https://blog.csdn.net/hnjzsyjyj/article/details/119917795
https://blog.csdn.net/hnjzsyjyj/article/details/126488154
https://blog.csdn.net/pspdragon/article/details/78726016

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值