现在的位置: 首页 > 综合 > 正文

最大流poj1273

2013年09月03日 ⁄ 综合 ⁄ 共 1856字 ⁄ 字号 评论关闭
//  BFS 的 Edmonds_Karp

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

const int N = 210;//顶点最多个数
const int INF = 0x7FFFFFFF;//无穷大
int n,m,map[N][N],path[N],flow[N],start,end;//n为顶点,m为边,map为邻接矩阵
queue<int> q;

int bfs()
{
    int i,t;
    while (!q.empty()) q.pop();
    memset(path,-1,sizeof(path));
    path[start]=0,flow[start]=INF;
    q.push(start);
    while (!q.empty())
    {
        t=q.front();
        q.pop();
        if (t==end) break;
        for (i=1;i<=n;i++)
        {
            if (i!=start && path[i]==-1 && map[t][i])
            {
                flow[i]=flow[t]<map[t][i]?flow[t]:map[t][i];
                q.push(i);
                path[i]=t;
            }
        }
    }
    if (path[end]==-1) return -1;
    return flow[n];                   //一次遍历之后的流量增量
}

int Edmonds_Karp()//从start到end的最大流
{
    int max_flow=0,step,now,pre;
    while ((step=bfs())!=-1) //找不到增路径时退出
    {
        max_flow+=step;
        now=end;
        while (now!=start)
        {
            pre=path[now];
            map[pre][now]-=step;      //更新正向边的实际容量
            map[now][pre]+=step;      //添加反向边
            now=pre;
        }
    }
    return max_flow;
}

int main()
{
    int i,u,v,cost;
    while (scanf("%d %d",&m,&n)!=EOF)
    {
        memset(map,0,sizeof(map));
        for (i=0;i<m;i++)
        {
            scanf("%d %d %d",&u,&v,&cost);
            map[u][v]+=cost;           //not just only one input
        }
        start=1,end=n;
        printf("%d\n",Edmonds_Karp());
    }
    return 0;
}

 

 

// Ford_Fulkerson
//最大流问题
#include  <iostream>
#include  <queue>
using namespace std;

int m,n,a,b,c,cost[201][201];
int Pre[201],Min[201],M=10000001;
bool visit[201];

int Bfs()
{
    queue<int>  q;
    int temp;
    visit[1]=true;
    Pre[1]=0;
    Min[1]=M;
    q.push(1);
    while (!q.empty())
    {
        temp=q.front();
        q.pop();
        if (temp==m)  break;
        for (int i=1;i<=m;i++)
        {
            if (!visit[i]&&cost[temp][i])
            {
                Min[i]=(Min[temp]<cost[temp][i]) ? Min[temp] : cost[temp][i];
                Pre[i]=temp;
                visit[i]=true;
                q.push(i);
            }
        }
    }
    if (!visit[m]) return -1;
    else return   Min[m];
}

int Ford_Fulkerson()//求顶点1(源点)到顶点n(汇点)的最大流 
{
    int f,Max_Flow=0;
    while ((f=Bfs())!=-1)
    {
        int temp=m;
        Max_Flow+=f;
        memset(visit,false,sizeof(visit));
        while (temp!=1)
        {
            int r=Pre[temp];
            cost[r][temp]-=f;
            cost[temp][r]+=f;
            temp=r;
        }
    }
    return Max_Flow;
}

int main()
{
    while (scanf("%d%d",&n,&m)!=EOF)
    {
        memset(cost,0,sizeof(cost));
        for (int i=1;i<=n;i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            cost[a][b]+=c;
        }
        printf("%d\n",Ford_Fulkerson());
    }
    return 0;
}

 

抱歉!评论已关闭.