Cod sursa(job #1223301)

Utilizator assa98Andrei Stanciu assa98 Data 26 august 2014 15:13:45
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

#define pe pair<int, int>
#define mp make_pair
#define fi first
#define se second

using namespace std;

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

const int MAX_N = 260;
const int INF = 20000000;

int c[MAX_N][MAX_N];
int f[MAX_N][MAX_N];
int n;
int S, D;
int ans;

int d[MAX_N];
int dad[MAX_N];

vector<pe> A[MAX_N];

int bellman() {
    queue<int> Q;

    for(int i = 1; i <= n; i++) {
        d[i] = INF;
        dad[i] = 0;
    }

    d[S] = 0;
    Q.push(S);

    while(!Q.empty()) {
        int nod = Q.front();
        Q.pop();
        if(nod == D) {
            continue;
        }

        for(auto it : A[nod]) {
            if(f[nod][it.fi] < c[nod][it.fi]) {
                if(d[nod] + it.se < d[it.fi]) {
                    d[it.fi] = d[nod] + it.se;
                    Q.push(it.fi);
                    dad[it.fi] = nod;
                }
            }
        }
    }

    return d[D];
}

void maxflow() { 
    int x = bellman();
    while(x < INF) {
        int fl = INF;
        for(int nod = D; nod != S; nod = dad[nod]) {
            fl = min(fl, c[dad[nod]][nod] - f[dad[nod]][nod]);
        }
        for(int nod = D; nod != S; nod = dad[nod]) {
            f[dad[nod]][nod] += fl;
            f[nod][dad[nod]] -= fl;
        }
        ans += fl * x;
        x = bellman();
    }
}

int main() {
    int  m;
    fin >> n >> m >> S >> D;

    for(int i = 1; i <= m; i++) {
        int a, b, x, y;
        fin >> a >> b >> x >> y;
        A[a].push_back(mp(b, y));
        A[b].push_back(mp(a, -y));
        c[a][b] = x;
    }

    maxflow();
    fout << ans;
    return 0;
}