首页 > 代码库 > 最大流模板

最大流模板

#include<iostream>#include<cstdio>#include<cstring>#include<queue>#include<algorithm>using namespace std;int pre[500],flow[500][500],dis[500];int map[500][500];int maxflow;int n,m;int ek(int begin ,int end){    int i,x;    maxflow=0;    queue<int>p;    while(!p.empty())    {        p.pop();    }    memset(flow,0,sizeof(flow));    while(1)    {        memset(dis,0,sizeof(dis));        dis[begin]=9999999;        p.push(begin);        while(!p.empty())        {            x=p.front();            p.pop();            for(i=1; i<=m; i++)            {                if(map[x][i]>flow[x][i]&&!dis[i])                {                    p.push(i);                    pre[i]=x;                    dis[i]=min(dis[x],map[x][i]-flow[x][i]);                }            }        }        if(dis[end]==0)        {            return maxflow;        }        for(i=end; i!=begin; i=pre[i])        {            flow[pre[i]][i]+=dis[end];            flow[i][pre[i]]-=dis[end];        }        maxflow+=dis[end];    }}int main(){    int i,u,v,w;    while(scanf("%d%d",&n,&m)!=EOF)    {        memset(map,0,sizeof(map));        memset(pre,0,sizeof(pre));        for(i=1; i<=n; i++)        {            scanf("%d%d%d",&u,&v,&w);            map[u][v]+=w;        }        printf("%d\n",ek(1,m));    }    return 0;}