前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >图论--网络流--最小费用流最大流模板

图论--网络流--最小费用流最大流模板

作者头像
风骨散人Chiam
发布2020-10-28 11:32:02
6540
发布2020-10-28 11:32:02
举报
文章被收录于专栏:CSDN旧文CSDN旧文
代码语言:javascript
复制
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#define INF 1e9
using namespace std;
const int maxn= 1000+10;
 
struct Edge
{
    int from,to,cap,flow,cost;
    Edge(){}
    Edge(int f,int t,int c,int fl,int co):from(f),to(t),cap(c),flow(fl),cost(co){}
};
 
struct MCMF
{
    int n,m,s,t;
    vector<Edge> edges;
    vector<int> G[maxn];
    bool inq[maxn];
    int d[maxn];
    int p[maxn];
    int a[maxn];
 
    void init(int n,int s,int t)
    {
        this->n=n, this->s=s ,this->t=t;
        edges.clear();
        for(int i=0;i<n;++i) G[i].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));
        m = edges.size();
        G[from].push_back(m-2);
        G[to].push_back(m-1);
    }
 
    bool BellmanFord(int &flow,int &cost)
    {
        for(int i=0;i<n;++i) d[i]=INF;
        memset(inq,0,sizeof(inq));
        queue<int> Q;
        d[s]=0,inq[s]=true,a[s]=INF,p[s]=0;
        Q.push(s);
 
        while(!Q.empty())
        {
            int u=Q.front(); Q.pop();
            inq[u]=false;
 
            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]) { inq[e.to]=true; Q.push(e.to); }
                }
            }
        }
        if(d[t]==INF) return false;
        flow += a[t];
        cost += a[t]*d[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;
    }
 
    int solve()
    {
        int flow=0,cost=0;
        while(BellmanFord(flow,cost));
        return cost;
    }
}MM;
 
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)==2)
    {
        int src=0,dst=n+1;
        MM.init(n+2,src,dst);
        MM.AddEdge(src,1,2,0);
        MM.AddEdge(n,dst,2,0);
        while(m--)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            MM.AddEdge(u,v,1,w);
            //MM.AddEdge(v,u,1,w);
        }
        printf("%d\n",2*MM.solve());
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档