码迷,mamicode.com
首页 > 其他好文 > 详细

luogu3381 【模板】最小费用最大流

时间:2017-12-21 20:05:54      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:最大   ons   main   int   names   val   cin   cost   post   

每次选代价最小的流增广

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
struct Edge{
    int too, nxt, val, cst;
}edge[100005];
int n, m, ss, tt, maxFlow, minCost, uu, vv, ww, xx, hea[5005], cnt;
int dis[5005], pre[5005];
bool vis[5005];
const int oo=0x3f3f3f3f;
queue<int> d;
void add_edge(int fro, int too, int val, int cst){
    edge[cnt].nxt = hea[fro];
    edge[cnt].too = too;
    edge[cnt].val = val;
    edge[cnt].cst = cst;
    hea[fro] = cnt++;
}
bool spfa(){
    memset(dis, 0x3f, sizeof(dis));
    memset(pre, -1, sizeof(pre));
    dis[ss] = 0;
    d.push(ss);
    vis[ss] = true;
    while(!d.empty()){
        int x=d.front();
        d.pop();
        vis[x] = false;
        for(int i=hea[x]; i!=-1; i=edge[i].nxt){
            int t=edge[i].too;
            if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
                dis[t] = dis[x] + edge[i].cst;
                pre[t] = i;
                if(!vis[t]){
                    vis[t] = true;
                    d.push(t);
                }
            }
        }
    }
    return dis[tt]!=oo;
}
void mcmf(){
    while(spfa()){
        int tmp=oo;
        for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
            tmp = min(tmp, edge[i].val);
        for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
            edge[i].val -= tmp;
            edge[i^1].val += tmp;
            minCost += edge[i].cst * tmp;
        }
        maxFlow += tmp;
    }
}
int main(){
    cin>>n>>m>>ss>>tt;
    memset(hea, -1, sizeof(hea));
    for(int i=1; i<=m; i++){
        scanf("%d %d %d %d", &uu, &vv, &ww, &xx);
        add_edge(uu, vv, ww, xx);
        add_edge(vv, uu, 0, -xx);
    }
    mcmf();
    cout<<maxFlow<<" "<<minCost<<endl;
    return 0;
}

luogu3381 【模板】最小费用最大流

标签:最大   ons   main   int   names   val   cin   cost   post   

原文地址:http://www.cnblogs.com/poorpool/p/8082170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!