Cod sursa(job #1815707)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 25 noiembrie 2016 18:07:29
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <cstdio>
#include <algorithm>
#include <queue>

using namespace std;

const int nmax = 350 + 10;
const int inf = 0x3f3f3f3f;

int n, m, S, D, ans;
int dad[nmax], bst[nmax];
vector < int > g[nmax];

int c[nmax][nmax], p[nmax][nmax], f[nmax][nmax];

void add_edge(int x, int y, int cap, int cost) {
    g[x].push_back(y);
    g[y].push_back(x);

    c[x][y] = cap;

    p[x][y] = cost;
    p[y][x] = -cost;

    f[x][y] = f[y][x] = 0;
}

void input() {
    scanf("%d %d %d %d", &n, &m, &S, &D);
    for (int i = 1; i <= m; ++i) {
        int x, y, c, z;
        scanf("%d %d %d %d", &x, &y, &c, &z);

        add_edge(x, y, c, z);
    }
}

bool bfs(int node) {
    for (int i = 1; i <= n; ++i) dad[i] = 0, bst[i] = inf;
    dad[S] = S;

    priority_queue < pair < int, int > > pq; pq.push({0, S}); bst[S] = 0;
    while ((int)pq.size()) {
        int node, cost; tie(cost, node) = pq.top(); pq.pop();

        if (bst[node] < -cost)
            continue;

        for (auto &it : g[node]) {
            if (f[node][it] < c[node][it] && bst[it] > bst[node] + p[node][it]) {
                bst[it] = bst[node] + p[node][it];
                dad[it] = node;
                pq.push({-bst[it], it});
            }
        }
    }

    return dad[D];
}

void solve() {
    while (bfs(S)) {
        int add = inf;
        for (int node = D; node != S; node = dad[node])
            add = min(add, c[dad[node]][node] - f[dad[node]][node]);

        ans += bst[D] * add;
        for (int node = D; node != S; node = dad[node])
            f[dad[node]][node] += add, f[node][dad[node]] -= add;
    }
}

void output() {
    printf("%d\n", ans);
}

int main() {
    freopen("fmcm.in","r",stdin);
    freopen("fmcm.out","w",stdout);

    input();
    solve();
    output();

    return 0;
}