费用流模板

#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int M=5010,ME=100000;
int INF=0x3fffffff;
class MaxFlow
{
public:
    void clear()
    {
        CLR(Head,-1);top=0;CLR(Flow,0);
    }
    void add(int u,int v,int cap,int cost)
    {
        Next[top] = Head[u];
        Num[top] = v;
        Cap[top] = cap;
        Cost[top] = cost;
        Head[u] = top++;

        Next[top] = Head[v];
        Num[top] = u;
        Cap[top] = 0;
        Cost[top] = -cost;
        Head[v] = top++;
    }
    int GetMinCostMaxFlow(int s,int t) //返回最终的cost
    {
        int cost = 0;
        while(SPFA(s,t))
        {
            int cur = t,minflow = INF;
            while(cur != s)
            {
                if(minflow > Cap[pre_edge[cur]]-Flow[pre_edge[cur]])
                    minflow = Cap[pre_edge[cur]]-Flow[pre_edge[cur]];
                cur = Num[pre_edge[cur] ^ 1];
            }
            cur = t ;
            while(cur != s)
            {
                Flow[pre_edge[cur]] += minflow;
                Flow[pre_edge[cur] ^ 1] -= minflow;
                cost += minflow * Cost[pre_edge[cur]];
                cur = Num[pre_edge[cur] ^ 1];
            }
        }
        return cost;
    }
private:
    bool SPFA(int s,int t)
    {
        fill(Len,Len+M,-INF);
        Len[s]=0;
        int head = -1,tail = -1,cur;
        Q[++head] = s;
        while(head != tail)
        {
            ++tail;
            if(tail >= M) tail -= M;
            cur = Q[tail];
            for(int i = Head[cur];i != -1;i = Next[i])
            {
                if(Cap[i]>Flow[i] && Len[Num[i]] < Len[cur] + Cost[i])
                {
                    Len[Num[i]] = Len[cur] + Cost[i];
                    ++head;
                    if(head >= M) head -= M;
                    pre_edge[Num[i]] = i;
                    Q[head] = Num[i];
                }
            }
        }
        return Len[t] != -INF;
    }
    int Head[M],Next[ME],Num[ME],Flow[ME],Cap[ME],Cost[ME],Q[ME],InQ[M],Len[M],pre_edge[M],top;
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值