luogu P2604 [ZJOI2010]网络扩容 |费用流

题目描述

给定一张有向图,每条边都有一个容量\(C\)和一个扩容费用\(W\)。这里扩容费用是指将容量扩大1所需的费用。求: 1、 在不扩容的情况下,1到N的最大流; 2、 将1到N的最大流增加K所需的最小扩容费用。

输入格式

输入文件的第一行包含三个整数\(N,M,K\),表示有向图的点数、边数以及所需要增加的流量。 接下来的M行每行包含四个整数\(u,v,C,W\),表示一条从u到v,容量为C,扩容费用为W的边。

输出格式

输出文件一行包含两个整数,分别表示问题1和问题2的答案。


利用残余网络,建边add(u,v,inf,c),把原图边权删掉

连边add(s,1,k,0)强制增加的流量为k

跑费用流

#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e4+10,M=2e5+10,inf=0x3f3f3f3f;
int n,m,s,t;
int nxt[M],head[N],go[M],edge[M],cost[M],tot=1;
inline void add(int u,int v,int o1,int o2){
    nxt[++tot]=head[u],head[u]=tot,go[tot]=v,edge[tot]=o1,cost[tot]=o2;
    nxt[++tot]=head[v],head[v]=tot,go[tot]=u,edge[tot]=0,cost[tot]=-o2;    
}
int dis[N],ret;
bool vis[N];
inline bool spfa(){
    memset(dis,0x3f,sizeof(dis)); 
    queue<int>q; q.push(s),dis[s]=0,vis[s]=1;
    while(q.size()){
        int u=q.front(); q.pop(); vis[u]=0;
        for(int i=head[u];i;i=nxt[i]){
            int v=go[i];
            if(edge[i]&&dis[v]>dis[u]+cost[i]){
                dis[v]=dis[u]+cost[i];
                if(!vis[v])q.push(v),vis[v]=1;
            }
        }
    }
    return dis[t]!=inf;
}
int dinic(int u,int flow){
    if(u==t)return flow;
    vis[u]=1;
    int rest=flow,k;
    for(int i=head[u];i&&rest;i=nxt[i]){
        int v=go[i];
        if(!vis[v]&&edge[i]&&dis[v]==dis[u]+cost[i]){
            k=dinic(v,min(edge[i],rest));
            if(k)ret+=k*cost[i],edge[i]-=k,edge[i^1]+=k,rest-=k;
            else dis[v]=-1;
        }
    }
    vis[u]=0;
    return flow-rest;
}
int k;
struct node{
    int u,v,o1,o2;
}e[M];
signed main(){
    scanf("%d%d%d", &n, &m, &k);
    for(int i=1,u,v,w,c;i<=m;i++){
        scanf("%d%d%d%d", &u, &v, &w, &c);
        e[i]=(node){u,v,w,c};
        add(u,v,w,c);
    }
    s=1,t=n;
    int flow=0,maxflow=0;
    while(spfa())
    while(flow=dinic(s,inf))maxflow+=flow;
    cout<<maxflow<<' ';
    memset(cost,0,sizeof(cost));
    s=0; add(s,1,k,0);
    for(int i=1;i<=m;i++)add(e[i].u,e[i].v,inf,e[i].o2);
    ret=flow=maxflow=0;
    while(spfa())
    while(flow=dinic(s,inf))maxflow+=flow;
    cout<<ret<<endl;
}

猜你喜欢

转载自www.cnblogs.com/naruto-mzx/p/12208462.html