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

洛谷 [P3381] 最小费用最大流模版

时间:2018-04-04 12:48:58      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:i++   markdown   str   source   oid   模版   for   ace   mat   

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXN = 5005;
int init() {
    int rv = 0, fh = 1;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-') fh = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        rv = (rv<<1) + (rv<<3) + c  - '0';
        c = getchar();
    }
    return fh * rv;
}
int head[MAXN], nume, n, m, mincost, maxflow, ss, tt, delta, dis[MAXN], pre[MAXN];
bool f[MAXN];
struct edge{
    int to, nxt, flow, cap, cost;
}e[MAXN * 30];
void adde(int from, int to, int cap, int cost) {
    e[++nume].to = to;
    e[nume].cap = cap;
    e[nume].cost = cost;
    e[nume].nxt = head[from];
    head[from] = nume;
}
queue <int> q;
bool SPFA() {
    memset(dis, 0x3f, sizeof(dis));
    memset(pre, 0, sizeof(pre));
    q.push(ss); dis[ss] = 0; pre[ss] = 0; f[ss] = 1;
    while(!q.empty()) {
        int u = q.front(); q.pop();
        f[u] = 0;
        for(int i = head[u]; i; i = e[i].nxt) {
            int v = e[i].to;
            if(e[i].flow < e[i].cap && dis[v] > dis[u] + e[i].cost) {
                dis[v] = dis[u] + e[i].cost;
                pre[v] = i;
                if(!f[v]) {
                    q.push(v); f[v] = 1;
                }
            }
        }
    }
    return dis[tt] != 0x3f3f3f3f;
}
void MCMF() {
    while(SPFA()) {
        delta = 0x3f3f3f3f;
        for(int i = pre[tt]; i; i = pre[e[(((i - 1) ^ 1) + 1)].to])
            delta = min(delta, e[i].cap - e[i].flow);
        for(int i = pre[tt]; i; i = pre[e[((i - 1) ^ 1) + 1].to]) {
            e[i].flow += delta;
            e[((i - 1) ^ 1) + 1].flow -= delta;
            mincost += delta * e[i].cost;
        }
        maxflow += delta;
    }
}
int main() {
    n = init(); m = init(); ss = init(); tt = init();
    for(int i = 1; i <= m; i++) {
        int u = init(), v = init(), cap = init(), cost = init();
        adde(u, v, cap, cost); adde(v, u, 0, -cost);
    }
    MCMF();
    printf("%d %d\n", maxflow, mincost);
    return 0;
}

洛谷 [P3381] 最小费用最大流模版

标签:i++   markdown   str   source   oid   模版   for   ace   mat   

原文地址:https://www.cnblogs.com/Mr-WolframsMgcBox/p/8715667.html

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