Cod sursa(job #1165589)

Utilizator cbanu96Banu Cristian cbanu96 Data 2 aprilie 2014 19:25:59
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

#define FILEIN "fmcm.in"
#define FILEOUT "fmcm.out"
#define INF 0x3f3f3f3f
#define NMAX 355

vector<int> A[NMAX];

int Cost[NMAX][NMAX], Cap[NMAX][NMAX], F[NMAX][NMAX], D[NMAX], T[NMAX];
bool Used[NMAX];

queue<int> Q;

int N, M;

long long Augment(int source, int sink) {
    memset(Used, 0, sizeof(Used));
    memset(D, INF, sizeof(D));

    Used[source] = 1;
    D[source] = 0;
    Q.push(source);

    while (!Q.empty()) {
        int x = Q.front();
        Q.pop();

        for ( int i = 0; i < A[x].size(); i++ ) {
            int y = A[x][i];

            if (Cap[x][y] - F[x][y] > 0 && D[x] + Cost[x][y] < D[y]) {
                D[y] = D[x] + Cost[x][y];
                T[y] = x;
                if (!Used[y]) {
                    Used[y] = 1;
                    Q.push(y);
                }
            }
        }

        Used[x] = 0;
    }

    if (D[sink] == INF)
        return 0;

    int fmin = INF;
    for ( int i = sink; i != source; i = T[i] )
        fmin = min(fmin, Cap[T[i]][i] - F[T[i]][i]);

    for ( int i = sink; i != source; i = T[i] ) {
        F[T[i]][i] += fmin;
        F[i][T[i]] -= fmin;
    }

    return fmin * D[sink];
}

long long FMCM(int source, int sink) {
    long long partial;
    long long total = 0;
    while (partial = Augment(source, sink)) {
        total += partial;
    }

    return total;
}

int main() {
    freopen(FILEIN, "r", stdin);
    freopen(FILEOUT, "w", stdout);

    int S, D;

    scanf("%d %d %d %d", &N, &M, &S, &D);

    for ( int i = 1, x, y, z, c; i <= M; i++ ) {
        scanf("%d %d %d %d", &x, &y, &c, &z);

        A[x].push_back(y);
        A[y].push_back(x);

        Cap[x][y] = c;
        Cost[x][y] = z;
        Cost[y][x] = -z;
    }

    printf("%lld\n", FMCM(S, D));
    return 0;
}