Cod sursa(job #743111)

Utilizator deneoAdrian Craciun deneo Data 3 mai 2012 11:27:09
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;

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

#define MAXN 400
#define pb push_back
#define inf 0x3f3f3f
#define ll long long

vector<int> g[MAXN];
int n, m, S, D, drum = 1;
int cost[MAXN][MAXN], flux[MAXN][MAXN], cap[MAXN][MAXN], dist[MAXN];

ll BellmanFord() {
    int nod, i, used[MAXN], from[MAXN];
    queue<int> q;

    for (i = 1; i <= n; ++i)
        dist[i] = inf;

    q.push(S);
    dist[S] = 0;
    memset(used, 0, sizeof(used));
    used[S] = 1;

    while(!q.empty()) {
        nod = q.front();
        q.pop();
        for (i = 0; i < g[nod].size(); ++i) {
            if (cap[nod][g[nod][i]] - flux[nod][g[nod][i]] > 0 && dist[nod] + cost[nod][g[nod][i]] < dist[g[nod][i]]) {
                dist[g[nod][i]] = dist[nod] + cost[nod][g[nod][i]];
                from[g[nod][i]] = nod;
                if (!used[g[nod][i]]) {
                    used[g[nod][i]] = 1;
                    q.push(g[nod][i]);
                }
            }
        }
    }
    if(dist[D] == inf) {
        drum = 0;
        return 0;
    }
    int vmin = inf;

    for (i = D; i != S; i = from[i])
        vmin = min(vmin, cap[from[i]][i] - flux[from[i]][i]);
    for (i = D; i != S; i = from[i]) {
        flux[from[i]][i] += vmin;
        flux[i][from[i]] -= vmin;
    }

    return vmin * dist[D];
}


ll doFlux() {
    ll rez = 0;
    while(drum) {
        rez += BellmanFord();
    }
    return rez;
}

int main() {
    int i, x, y, c, z;
    fin >> n >> m >> S >> D;
    for (i = 1; i <= m; ++i) {
        fin >> x >> y >> c >> z;
        g[x].pb(y);
        g[y].pb(x);
        cap[x][y] = c;
        cost[x][y] = z;
        cost[y][x] = -z;
    }

    fout << doFlux() << "\n";
    fout.close();
    return 0;
}