[最小费用最大流模板]MCMF模板

#include<bits/stdc++.h>
#define maxn 210
#define maxm 80100
#define INF 0x3f3f3f3f
using namespace std;
struct node{
    int  to, ne, w, cost;
}e[maxm];
int head[maxn], cnt;
int pre[maxn];//记录增广路径上 到达点i的边的编号
int dis[maxn];
bool vis[maxn];
int n, m;
int S, T;
void init(){
    cnt = 0;
    memset(head, -1, sizeof(head));
}
void add(int u, int v, int w, int c){
    e[cnt] = (node){v, head[u], w, c};    head[u] = cnt++;
    e[cnt]= (node){u, head[v], 0, -c,};   head[v] = cnt++;
}
queue<int>q;
int flow[maxn];
bool SPFA(){
    while(!q.empty()) q.pop();
    memset(dis, INF, sizeof(dis));
    memset(vis, false, sizeof(vis));
    memset(flow,INF,sizeof(flow));
    memset(pre, -1, sizeof(pre));
    dis[S] = 0;vis[S] = 1;
    q.push(S);
    while(!q.empty()){
        int u = q.front(); q.pop();
        vis[u] = 0;
        for(int i = head[u]; i != -1; i = e[i].ne){
            int v=e[i].to;
            if(dis[v] > dis[u] + e[i].cost && e[i].w){
                flow[v]=min(flow[u],e[i].w);
                dis[v] = dis[u] + e[i].cost;
                pre[v] = i;//记录前驱边 的编号
                if(!vis[v])  vis[v] = 1,q.push(v);
            }
        }
    }
    return ~pre[T];//可达返回true
}
void MCMF(int &c, int &f){
    f=c=0;
    while(SPFA()){
        int i=pre[T],d=flow[T];
        while(~i){
            e[i].w-=d;
            e[i^1].w+=d;
            i=pre[e[i^1].to];
        }
        f+=d;c+=d*dis[T];
    }
}
void getMap(){
    S=m+n+1;T=S+1;

}

int main(){
    while(scanf("%d%d", &m, &n)!=EOF){
        init();
        getMap();//建图
        int cost, flow;//最小费用 最大流
        MCMF( cost, flow);
        printf("%d\n", cost);//最小费用 最大流
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值