Cod sursa(job #1865535)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 1 februarie 2017 20:07:44
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <queue>
#define ll long long
#define maxn 505
#define maxx 1000010

using namespace std;

ifstream in("fmcm.in");
ofstream out("fmcm.out");

vector <int> ls[maxn];
ll cap[maxn][maxn], f[maxn][maxn], cs[maxn][maxn], dist[maxn], fmin, sol;
const ll f_mare = 2e11;
int n, m, inc, sf, x, y, z, t, tt[maxn], g[maxn], i;
int coada[maxx], st, dr;
bool viz[maxn], ok;

ll bf() {
    for (i = 1; i <= n; i++) {
        dist[i] = f_mare;
        tt[i] = -1;
    }
    dist[inc] = 0;

    st=dr=0, coada[dr] = inc;
    viz[inc] = 1;
    while (st <= dr) {
        x = coada[st++];
        viz[x]=0;
        for (i = 0; i < g[x]; i++) {
            y = ls[x][i];
            if (dist[y] > dist[x] + cs[x][y] && cap[x][y]-f[x][y] > 0) {
                if (!viz[y]) {coada[++dr] = y; viz[y] = 1;}
                dist[y] = dist[x] + cs[x][y];
                tt[y] = x;
            }
        }
    }
    if (dist[y] < f_mare) {
        ok = 1;
        fmin = f_mare;
        y = sf;
        while (y != inc) {
            fmin = min(fmin, cap[tt[y]][y] - f[tt[y]][y]);
            y = tt[y];
        }

        y = sf;
        while (y != inc) {
            f[tt[y]][y] += fmin;
            f[y][tt[y]] -= fmin;
            y = tt[y];
        }
        return dist[sf]*fmin;
    }
    return 0;
}

void calc() {

    ok=1;
    while (ok) {
        ok = 0;
        sol += bf();
    }

}

int main() {
    in >> n >> m >> inc >> sf;
    while (m--) {
        in >> x >> y >> z >> t;
        ls[x].push_back(y);
        ls[y].push_back(x);
        cap[x][y] = z;
        cs[x][y] = t;
        cs[y][x] = -t;
    }
    for (i = 1; i <= n; i++)
        g[i] = ls[i].size();
    calc();
    out << sol;
    return 0;
}