Cod sursa(job #1397081)

Utilizator irimiecIrimie Catalin irimiec Data 23 martie 2015 11:35:14
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 kb
#include <bits/stdc++.h>

using namespace std;

#define     mp              make_pair
#define     fs              first
#define     sc              second
#define     pob             pop_back
#define     pub             push_back
#define     eps             1E-7
#define     sz(a)           a.size()
#define     count_one       __builtin_popcount;
#define     count_onell     __builtin_popcountll;
#define     fastIO          ios_base::sync_with_stdio(false)
#define     PI              (acos(-1.0))
#define     linf            (1LL<<62)//>4e18
#define     inf             (0x7f7f7f7f)//>2e9

#define MAXN 360

#ifndef ONLINE_JUDGE
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
#endif

int n, m, s, d;
vector<int> vec[MAXN];
bitset<MAXN> viz;
bool bvalid = true;
int minflow;
int cap[MAXN][MAXN];
int flow[MAXN][MAXN];
int cost[MAXN][MAXN];
int dist[MAXN], fn[MAXN];

long long bford() {
    long long len = 0;
    queue<int> Q;

    for(int i = 1; i <= n; ++i)
        dist[i] = inf, fn[i] = -1;

    viz.reset();
    dist[s] = 0;
    Q.push(s);
    viz[s] = 1;

    int nod;
    while(!Q.empty()) {
        nod = Q.front(); Q.pop();
        for(auto it : vec[nod]) {
            if(cap[nod][it] - flow[nod][it] > 0 && dist[it] > cost[nod][it] + dist[nod]) {
                dist[it] = cost[nod][it] + dist[nod];
                fn[it] = nod;
                if(!viz[it]) {
                    Q.push(it);
                    viz[it] = true;
                }
            }
        }
    }

    if(dist[d] != inf) {
        minflow = inf;
        bvalid = true;

        for(int nod = d; nod != s; nod = fn[nod]) {
            minflow = min(minflow, cap[fn[nod]][nod] - flow[fn[nod]][nod]);
        }

        for(int nod = d; nod != s; nod = fn[nod]) {
            flow[fn[nod]][nod] += minflow;
            flow[nod][fn[nod]] -= minflow;
        }

        return minflow * dist[d];
    }

    return 0;
}

long long flux() {
    long long rez = 0;
    bvalid = true;

    while(bvalid) {
         bvalid = 0;
         rez += bford();
    }

    return rez;
}

int main() {
    fin >> n >> m >> s >> d;

    int x, y, z, c;
    for(int i = 0; i < m; ++i) {
        fin >> x >> y >> z >> c;
        vec[x].pub(y);
        vec[y].pub(x);
        cap[x][y] = z;
        cost[x][y] = c;
        cost[y][x] = -c;
    }

    fout << flux();
    return 0;
}