最小费用最大流

学习了一下最小费用最大流,发现其实就是在原来每条边的定义加上一个单位流量的费用,so寻找增广路时采用贪心的思想,每次找费用和最小的路径即可。
废话少说,上代码:

//POJ2135
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define maxn 1005
#define maxm 10005
#define INF 0x7ffffff//被fff坑死QAQ~~~ 
using namespace std;
int flow,u,v,cost,n,m,id[maxn],head[maxn],q,s,t,x,y,num,d[maxn],inq[maxn],a[maxn],pre[maxn];

struct xx{
    int v,next,cap,cost;
}b[maxm*4];

void add(int u,int v ,int q,int cost)
{
    b[num]=(xx){v,head[u],q,cost};
    head[u]=num++;
    b[num]=(xx){u,head[v],0,-cost};
    head[v]=num++;
}

int Bellford(int s,int t,int& flow,int& cost)
{
    //memset(d,INF,sizeof(d));
    for (int i=0;i<=t;i++) d[i]=INF;
    memset(inq,0,sizeof(inq));
    d[s]=0;inq[s]=1;pre[s]=-1;a[s]=INF;id[s]=-1;
    queue <int> q;
    q.push(s);
    while(!q.empty())
    {
        int u=q.front();q.pop();
        inq[u]=0;
        for (int i=head[u];i!=-1;i=b[i].next)
        {
            int v=b[i].v;
            if (d[u]+b[i].cost<d[v]&&b[i].cap)
            {
                d[v]=d[u]+b[i].cost;
                pre[v]=u;
                id[v]=i;
                a[v]=min(a[u],b[i].cap);
                if (!inq[v]) inq[v]=1,q.push(v);
            }
        }
    }
    if (d[t]==INF) return 0;
    flow+=a[t];
    cost+=d[t]*a[t];
     u=t;
    while (u!=s)
    {
        b[id[u]].cap-=a[t];
        b[id[u]^1].cap+=a[t];
        u=pre[u];
    }
    return true;
}

int Mincost()
{
    flow=0,cost=0;
    while (Bellford(s,t,flow,cost));
    return cost;
}

int main()
{
    scanf("%d%d",&n,&m);
    num=0;s=0;t=n+1;
    memset(head,-1,sizeof(head));
    for (int i=1;i<=m;i++)
         scanf("%d%d%d",&x,&y,&q),add(x,y,1,q),add(y,x,1,q);
    add(s,1,2,0);add(n,t,2,0);
    printf("%d",Mincost());
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值