最大流问题

来源:互联网 发布:畑亚贵 知乎 编辑:程序博客网 时间:2024/05/19 12:36
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#define INF 100000//无穷
#define MAX 500//结点上限
#define Min(x,y) x<y?x:y
using namespace std;
int map[MAX][MAX];//网络
int flow[MAX][MAX];//可行流
int d[MAX];//首先做标志数组,然后做存储最大公共增量的数组。
int pre[MAX];//记录结点的父节点
int n,m;//n个顶点,m条边

int max_flow(int s,int t)//s,起点,t,汇点
{
    queue <int> q;
    int ans,u,v;
    ans=0;
    memset(flow,0,sizeof(flow));
    while(1)
    {
        memset(d,0,sizeof(d));
        memset(pre,0,sizeof(pre));
        d[s]=INF;
        q.push(s);
        while(!q.empty())//BFS寻找增广路径
        {
            u=q.front();
            q.pop();
            for (v=1;v<=n;v++)
            {
                if (!d[v] && map[u][v]>flow[u][v])//如果v结点没有访问过,并且该边没有饱和
                {
                    pre[v]=u;//记录父结点
                    q.push(v);
                    d[v]=Min(d[u],map[u][v]-flow[u][v]);//从父结点的增量与当前结点的增量中选最小的
                }
            }
        }
        if (d[t]==0) break;//如果汇未被标上号,即没有这样的顶点可选时,即为最大流
        for (u=t;u!=s;u=pre[u])//从汇点往源点,为可行流赋值
        {
            flow[pre[u]][u]+=d[t];//将公共增量加入flow
            flow[u][pre[u]]-=d[t];//若为负边,则减去a【t】
        }
        ans+=d[t];//最大流
    }
    return ans;
}

int main()
{
    int i,x,y,z;
    while(cin>>m>>n)
    {
        memset(map,0,sizeof(map));
        for (i=0;i<m;i++)
        {
            cin>>x>>y>>z;
            map[x][y]+=z;
        }
        int s=1,t=n;
        cout<<max_flow(s,t)<<endl;
    }
    return 0;
}

原创粉丝点击