【LOJ101】最大流(Edmonds-Karp)

problem

  • 给定n个点,m条边的有向图
  • 求源点s到汇点的最大流

solution

最大流模板,,不会看笔记吧。。。

codes

//Edmonds-Karp
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn = 110, maxm = 5010<<1;

int n, m, s, t;
int tot=1, head[maxn], Next[maxm], ver[maxm], flow[maxm];
void AddEdge(int x, int y, int z){
    ver[++tot] = y;  flow[tot] = z;
    Next[tot] = head[x];  head[x] = tot;
    ver[++tot] = x;  flow[tot] = 0;
    Next[tot] = head[y];  head[y] = tot;
}

LL infc[maxn], pre[maxn], maxflow;
bool vis[maxn];
bool bfs(){
    memset(vis,0,sizeof(vis));
    queue<int>q;
    q.push(s);  vis[s] = 1;  infc[s] = 1<<30;
    while(q.size()){
        int x = q.front();  q.pop();
        for(int i = head[x]; i; i = Next[i]){
            int y = ver[i];
            if(vis[y])continue;
            if(!flow[i])continue;//1.当前边无流量返回
            infc[y] = min(infc[x], (LL)flow[i]);//2.增广路上各边的最小剩余容量
            pre[y] = i;//3.方案
            vis[y] = 1;  q.push(y);
            if(y == t)return true;//4.到达汇点
        }
    }
    return false;
}
void update(){
    int x = t;
    while(x != s){
        int i = pre[x];
        flow[i] -= infc[t];
        flow[i^1] += infc[t];
        x = ver[i^1];
    }
    maxflow += infc[t];
}

int main(){
    cin>>n>>m>>s>>t;
    for(int i = 1; i <= m; i++){
        int x, y, z;  cin>>x>>y>>z;  AddEdge(x,y,z);
    }
    while(bfs())update();
    cout<<maxflow<<'\n';
    return 0;
}
posted @ 2018-06-02 20:39  gwj1139177410  阅读(153)  评论(0编辑  收藏  举报
选择