EK(BFS)求最大流的算法模板(邻接表)

来源:互联网 发布:云计算最大的特征是() 编辑:程序博客网 时间:2024/06/06 00:04
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <queue>#define inf 0x3f3f3f3fusing namespace std;int Map[300][300],path[300];int bfs(int st,int en){    queue<int> q;    int flow[300];    memset(flow,0,sizeof(flow));    //memset(path,0,sizeof(path));    while(!q.empty())        q.pop();    q.push(st);flow[st]=inf;path[st]=-1;    while(!q.empty())    {        int save=q.front();        q.pop();        if (save==en)            break;        for (int k=1;k<300;k++)            if (Map[save][k]&&!flow[k])        {            if (flow[save]<Map[save][k]) flow[k]=flow[save];            else flow[k]=Map[save][k];            path[k]=save;            q.push(k);        }    }    if (flow[en]==0) return -1;    return flow[en];}int Ford_f(int st,int en){    int max_f(0),flow(0);    flow=bfs(st,en);    while(flow!=-1)    {        for (int k=en;path[k]!=-1;k=path[k])        {            Map[path[k]][k]-=flow;            Map[k][path[k]]+=flow;        }        max_f+=flow;        flow=bfs(st,en);    }    return max_f;}int main(){    int m,n;    while(~scanf("%d %d",&n,&m))    {        memset(Map,0,sizeof(Map));        for (int k=1;k<=n;k++)        {            int a,b,c;            scanf("%d %d %d",&a,&b,&c);            Map[a][b]+=c;        }        printf("%d\n",Ford_f(1,m));    }    return 0;}


最大流的思想就去看kuangbin的博客吧,该说的都说了这里就是mark一下记个板子,但是这个板子时间复杂度较高,只能是适用于较小的数据,就直接用最方便的邻接表来存数据了,接下来会补一个时间复杂度较低的板子,那个东西我会用边存来节省空间复杂度

原创粉丝点击