bzoj 1834 [ZJOI2010] 网络扩容(费用流,残余网络)

题目

传送门

题解

第一问最大流,在建图的过程中把费用设为0
第二问把边重新再原图上连一遍,容量为inf(实际上为k就可以),费用为输入,设置新的源点向原来的源点之间连边,容量为k、费用为0;这样再跑最小费用最大流的时候就会优先经过残留网络的边(因为其费用为0)因此求出来的就是最小扩容费用

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=1000001;
const int inf=1e9;

queue <int> q;
int n,m,k,maxflow,mincost;
struct Edge{
    int next,to,flow,dis;
}edge[maxn<<1];
int num_edge=-1,head[maxn],last[maxn],pre[maxn],dis[maxn],flow[maxn];
int bian[maxn],tot;
int x[maxn],y[maxn],z[maxn],f[maxn];

void add_edge(int from,int to,int flow,int dis)
{
    edge[++num_edge].next=head[from];
    edge[num_edge].dis=dis;
    edge[num_edge].flow=flow;
    edge[num_edge].to=to;
    head[from]=num_edge;
}
void add(int x,int y,int z,int f) {add_edge(x,y,z,f); add_edge(y,x,0,-f);}

bool vis[maxn];
bool spfa(int s,int t)
{
    memset(dis,0x7f,sizeof(dis));
    memset(flow,0x7f,sizeof(flow));
    memset(vis,0,sizeof(vis));
    while (!q.empty()) q.pop();
    q.push(s); vis[s]=1; dis[s]=0; pre[t]=-1;
    while (!q.empty())
    {
        int now=q.front(); q.pop();
        vis[now]=0;
        for (int i=head[now]; i!=-1; i=edge[i].next)
        {
            int to=edge[i].to;
            if (edge[i].flow>0 && dis[to]>dis[now]+edge[i].dis)
            {
                dis[to]=dis[now]+edge[i].dis;
                flow[to]=min(flow[now],edge[i].flow);
                last[to]=i;
                pre[to]=now;
                if (!vis[to])
                {
                    q.push(to); vis[s]=1;
                }
            }
        }
    }
    return pre[t]!=-1;
}

void MCMF(int s,int t)
{
    while (spfa(s,t))
    {
        int now=t;
        maxflow+=flow[t];
        mincost+=dis[t]*flow[t];
        while (now!=s)
        {
            bian[++tot]=last[now];
            edge[last[now]].flow-=flow[t];
            edge[last[now]^1].flow+=flow[t];
            now=pre[now];
        }
    }
}

int main()
{
    memset(head,-1,sizeof(head));
    scanf("%d%d%d",&n,&m,&k);
    int S=1,T=n;
    for (int i=1; i<=m; i++)
    {
        scanf("%d%d%d%d",&x[i],&y[i],&z[i],&f[i]);
        add(x[i],y[i],z[i],0);
    }
    MCMF(S,T);
    printf("%d ",maxflow); maxflow=0; mincost=0;
    S=0; add(0,1,k,0);
    for (int i=1; i<=m; i++)
        add(x[i],y[i],inf,f[i]);
    MCMF(S,T);
    printf("%d",mincost);
    return 0;
}

总结

注意逆向思维;
总结残余网络的应用,可以搞一些事情——输出方案,在原图中加边、求最小扩容费用等

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值