【算法练习】BZOJ1877: [SDOI2009]晨跑 (网络流,最小费用最大流)

题意

n个点,m条单向边;每条边有费用(通过的时间),每条边只能走一次(流量限制),求用走的边尽可能多,并且时间尽可能短。(最小费用+最大流)

题解

最小费用最大流,然后建图的时候拆点,原因是只能经过一次。

代码

#include<bits/stdc++.h>
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
const int nmax = 1e6+7;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const ull p = 67;
const ull MOD = 1610612741;
int n,m;
struct MCMF{
    int final_flow,final_cost,tot,S,T;
    bool inque[nmax];
    int head[nmax],dis[nmax],pre_edge[nmax],pre_index[nmax],add_flow[nmax];
    struct edge{ int to,nxt,cap,flow,cost;}e[nmax<<1];
    void init(int S, int T){
        memset(head,-1,sizeof head);
        this->S = S, this->T = T;
    }
    void add_edge(int u, int v, int cap, int cost){
        e[tot].to = v, e[tot].nxt = head[u], e[tot].flow = 0, e[tot].cap = cap, e[tot].cost = cost, head[u] = tot++;
        e[tot].to = u, e[tot].nxt = head[v], e[tot].flow = 0, e[tot].cap = 0, e[tot].cost = -cost, head[v] = tot++;
    }
    bool spfa(){
        for(int i = S;i<=T;++i) inque[i] = false, dis[i] = i == S?0:INF;
        queue<int> q; q.push(S), inque[S] = true, add_flow[S] = INF;
        while(!q.empty()){
            int u = q.front(); q.pop(); inque[u] = false;
            for(int i = head[u];i!=-1;i=e[i].nxt){
                int v = e[i].to;
                if(e[i].cap > e[i].flow && dis[u] + e[i].cost < dis[v]){
                    dis[v] = dis[u] + e[i].cost, pre_edge[v] = i, pre_index[v] = u;
                    add_flow[v] = min(add_flow[u],e[i].cap - e[i].flow);
                    if(!inque[v]) q.push(v),inque[v] = true;
                }
            }
        }
        return dis[T] != INF;
    }
    void mincost_mxflow() {
        final_cost = final_flow = 0;
        while(spfa()){
            final_flow += add_flow[T];
            final_cost += add_flow[T] * dis[T];
            int now = T;
            while(now != S){
                e[pre_edge[now]].flow += add_flow[T];
                e[pre_edge[now]^1].flow -= add_flow[T];
                now = pre_index[now];
            }
        }
    }
}solver;

int main() {
    scanf("%d %d",&n,&m);
    int u,v,c;
    solver.init(0,2*n+1);
    for(int i = 1;i<=m;++i){
        scanf("%d %d %d",&u,&v,&c);
        solver.add_edge(u+n,v,1,c);
    }
    for(int i = 1;i<=n;++i) solver.add_edge(i,i+n,1,0);
    solver.add_edge(0,n+1,INF,0);
    solver.add_edge(n,2*n+1,INF,0);
    solver.mincost_mxflow();
    printf("%d %d\n",solver.final_flow,solver.final_cost);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值