Cod sursa(job #1969452)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 18 aprilie 2017 14:30:24
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;
vector < int > g[nmax];

int flow, flow_cost, S, D;
int dad[nmax], best[nmax], inq[nmax];
int f[nmax][nmax], c[nmax][nmax], cost[nmax][nmax];

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

    c[x][y] = cap;
    cost[x][y] = C; cost[y][x] = -C;
}

bool bellman() {
    memset(dad, -1, sizeof(dad));
    memset(best, inf, sizeof(best));
    memset(inq, 0, sizeof(inq));

    queue < int > q;

    q.push(S); inq[S] = 1; best[S] = 0;
    while (q.size()) {
        int node = q.front(); inq[node] = 0; q.pop();

        for (auto &it: g[node]) {
            if (f[node][it] == c[node][it]) continue;
            if (best[node] + cost[node][it] >= best[it]) continue;

            best[it] = best[node] + cost[node][it];
            dad[it] = node;

            if (!inq[it])
                q.push(it), inq[it] = 1;
        }
    }

    return (best[D] != inf);
}

void compute_flow() {
    while (bellman()) {
        int path_capacity = inf;
        for (int node = D; node != S; node = dad[node])
            path_capacity = min(path_capacity, c[dad[node]][node] - f[dad[node]][node]);

        flow += path_capacity;
        flow_cost += best[D] * path_capacity;

        for (int node = D; node != S; node = dad[node])
            f[dad[node]][node] += path_capacity,
            f[node][dad[node]] -= path_capacity;
    }
}

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

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

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

    compute_flow();
    printf("%d\n", flow_cost);

    return 0;
}