zoukankan      html  css  js  c++  java
  • 关于最小费用最大流的求解思路与模板

    大致思路就是运用SPFA,不断地求解最小费用的一条从原点到汇点的路径,然后增广一次;

    直到不能增广了,那么就得到了答案。

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<vector>
    #include<queue>
    #include<algorithm>
    using namespace std;
    
    //设置节点数量
    const int maxn=1000+10;
    
    const int INF=0x7FFFFFFF;
    struct Edge
    {
        int from,to,cap,flow,cost;
    };
    int n,m,len,s,t;
    vector<Edge> edges;
    vector<int> G[maxn];
    int inq[maxn];
    int d[maxn];
    int p[maxn];
    int a[maxn];
    
    
    void init()
    {
        for(int i=0; i<maxn; i++) G[i].clear();
        edges.clear();
    }
    
    void Addedge(int from,int to,int cap,int cost)
    {
        edges.push_back((Edge)
        {
            from,to,cap,0,cost
        });
        edges.push_back((Edge)
        {
            to,from,0,0,-cost
        });
        len=edges.size();
        G[from].push_back(len-2);
        G[to].push_back(len-1);
    }
    
    bool BellmanFord(int s,int t,int &flow,int &cost)
    {
    
        for(int i=0;i<maxn;i++) d[i]=INF;
    
        memset(inq,0,sizeof(inq));
        memset(p,-1,sizeof(p));
    
        d[s]=0;inq[s]=1;p[s]=0;a[s]=INF;
    
        queue<int>Q;
        Q.push(s);
        while(!Q.empty())
        {
            int u=Q.front();Q.pop();
            inq[u]=0;
            for(int i=0;i<G[u].size();i++)
            {
                Edge& e=edges[G[u][i]];
                if(e.cap>e.flow&&d[e.to]>d[u]+e.cost)
                {
                    d[e.to]=d[u]+e.cost;
                    p[e.to]=G[u][i];
                    a[e.to]=min(a[u],e.cap-e.flow);
                    if(!inq[e.to]){Q.push(e.to);inq[e.to]=1;}
                }
            }
        }
        if(d[t]==INF) return false;
        flow+=a[t];
        cost+=d[t]*a[t];
        int u=t;
        while(u!=s)
        {
            edges[p[u]].flow+=a[t];
            edges[p[u]^1].flow-=a[t];
            u=edges[p[u]].from;
        }
        return true;
    }
    
    void Mincost (int s,int t)
    {
        int flow=0,cost=0;
        while(BellmanFord(s,t,flow,cost));
        printf("最大流:%d
    ",flow);
        printf("最小费用:%d
    ",cost);
    }
    
    int main()
    {
        
        scanf("%d%d",&n,&m);
        //n个节点,m条边
        
        init();//初始化
        s=0;t=n+1;//设置源点和汇点
        
        /*
        加边
        格式:Addedge(起点,终点,容量,花费);
        */
        
        Mincost(s,t);
        
        return 0;
    }
  • 相关阅读:
    java语法基础
    HashMap中的put()和get()的实现原理
    理解:o(1), o(n), o(logn), o(nlogn) 时间复杂度
    mongodb去重分页查询支持排序
    elk日志分析系统搭建(window )亲自搭建
    IDEA更改主题插件——Material Theme UI
    css实现图片的瀑布流且右上角有计数
    C# string "yyMMdd" 转DataTime
    Vue.js系列(一):Vue项目创建详解
    VS2017常用快捷键
  • 原文地址:https://www.cnblogs.com/zufezzt/p/4685358.html
Copyright © 2011-2022 走看看