【洛谷 P2604】 [ZJOI2010]网络扩容(最大流,费用流)

题目链接
第一问就是简单的最大流。
第二问,保留第一问求完最大流的残量网络。
然后新建一个源点,向原源点连一条流量为k,费用为0的边。
然后所有边重新连一起(原来的边保留),费用为题目所给,最小费用即为第二问答案,很好理解。

#include <cstdio>
#include <queue>
#include <cstring>
#define INF 2147483647
using namespace std;
const int MAXN = 1010;
const int MAXM = 20010;
struct Edge{
    int from, next, to, rest, cost;
}e[MAXM];
int head[MAXN], num = 1, n, m, k;
inline void Add(int from, int to, int flow, int cost){
    e[++num] = (Edge){from, head[from], to, flow, cost}; head[from] = num;
    e[++num] = (Edge){to, head[to], from, 0, -cost}; head[to] = num;
}
int s, t, a[MAXM], b[MAXM], c[MAXM], d[MAXM], now, maxflow, mincost;
queue <int> q;
int v[MAXN], dis[MAXN], pre[MAXN], flow[MAXN];
int re(){
    q.push(s);
    memset(dis, 127, sizeof dis);
    memset(flow, 0, sizeof flow);
    dis[s] = 0; pre[t] = 0; flow[s] = INF;
    while(q.size()){
        now = q.front(); q.pop(); v[now] = 0;
        for(int i = head[now]; i; i = e[i].next)
           if(e[i].rest && dis[e[i].to] > dis[now] + e[i].cost){
             dis[e[i].to] = dis[now] + e[i].cost;
             pre[e[i].to] = i; flow[e[i].to] = min(flow[now], e[i].rest);
             if(!v[e[i].to]) v[e[i].to] = 1, q.push(e[i].to);
           }
    }
    return pre[t];
}
int main(){
    scanf("%d%d%d", &n, &m, &k); s = 1; t = n;
    for(int i = 1; i <= m; ++i){
       scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
       Add(a[i], b[i], c[i], 0);
    }
    while(re()){
        now = pre[t];
        while(now){
            e[now].rest -= flow[t];
            e[now ^ 1].rest += flow[t];
            now = pre[e[now].from];
        }
        maxflow += flow[t];
    }
    printf("%d ", maxflow);
    s = 0; Add(s, 1, k, 0);
    for(int i = 1; i <= m; ++i)
       Add(a[i], b[i], INF, d[i]);
    while(re()){
        now = pre[t];
        while(now){
            e[now].rest -= flow[t];
            e[now ^ 1].rest += flow[t];
            mincost += e[now].cost * flow[t];
            now = pre[e[now].from];
        }
    }
    printf("%d\n", mincost);
    return 0;
}

转载于:https://www.cnblogs.com/Qihoo360/p/10539654.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值