EK算法

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

const int  maxn=205;
#define INF 0x3f3f3f3f

int e[maxn][maxn];
bool vis[maxn];
int pre[maxn];
int n,m;

bool bfs(int s,int t){
    int p;
    queue<int> q;
    memset(pre,-1,sizeof(pre));
    memset(vis,0,sizeof(vis));
    pre[s]=s;
    vis[s]=1;
    q.push(s);
    while(!q.empty()){
        int u=q.front();
        if(u==t) return 1;
        q.pop();
        for(int i=1;i<=n;i++){
            if(e[u][i]&&!vis[i]){
                pre[i]=u;
                vis[i]=true;
                q.push(i);
            }
        }
    }
    return false;
}

int EK(int s,int t){
    int flow=0;
    int d,i;
    while(bfs(s,t)){
        d=INF;
        for(int i=t;i!=s;i=pre[i]){
            d=min(d,e[pre[i]][i]);
        }
        for(int i=t;i!=s;i=pre[i]){
            e[pre[i]][i]-=d;
            e[i][pre[i]]+=d;
        }
        flow+=d;
    }
    return flow;
}

int main()
{
    while(scanf("%d%d",&m,&n)!=EOF){
        int u,v,w;
        memset(e,0,sizeof(e));
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&u,&v,&w);
            e[u][v]=w;
        }
        printf("%d\n",EK(1,n));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/81103194