Cod sursa(job #730036)

Utilizator Mishu91Andrei Misarca Mishu91 Data 1 aprilie 2012 23:17:44
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

#define foreach(V) for(typeof (V).begin() it = (V).begin(); it != (V).end(); ++it)

const int MAX_N = 355;
const int INF = 0x3f3f;

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

vector <short> G[MAX_N];
short C[MAX_N][MAX_N], F[MAX_N][MAX_N], T[MAX_N];
short D[MAX_N], Cost[MAX_N][MAX_N];
short N, M, P, U;

/**
 * Read the data from the input file and create the vectors that contain the edges and the cost
 */
void read() {
    fin >> N >> M >> P >> U;

    while(M--)
    {
        short a, b, c, cost;
        fin >> a >> b >> c >> cost;

        G[a].push_back(b);
        G[b].push_back(a);
        C[a][b] = c;
        Cost[a][b] = cost;
        Cost[b][a] = -cost;
    }
}

/**
 * The comparation function for the priority queue, sorting the elements depending on the distance vector
 */
struct cmp {
    bool operator()(const short &a, const short &b) {
        return D[a] > D[b];
    }
};

/**
 * Return true if there is any flow from the source to the destination, and store the flow
 */
bool dijkstra() {
    for(int i = 1; i <= N; ++i) {
        D[i] = INF;
    }

    priority_queue <short, vector <short>, cmp > Q;
    bitset <MAX_N> inq;

    Q.push(P);
    D[P] = 0;
    inq[P] = 1;

    while(!Q.empty()) {
        short nod = Q.top();
        Q.pop();
        inq[nod] = 0;

        foreach(G[nod]) {
            if(C[nod][*it] > F[nod][*it] && D[nod] + Cost[nod][*it] < D[*it]) {
                D[*it] = D[nod] + Cost[nod][*it];
                T[*it] = nod;

                if(inq[*it]) continue;
                Q.push(*it);
                inq[*it] = 1;
            }
        }
    }
    return (D[U] < INF);
}

/**
 * Perform the flow algorithm
 */
void minFlow() {
    int fmin, flow = 0;
    while(dijkstra()) {
        fmin = INF;
        for(short i = U; i != P; i = T[i])
            fmin = min(fmin, C[T[i]][i] - F[T[i]][i]);

        for(short i = U; i != P; i = T[i]) {
            F[T[i]][i] += fmin;
            F[i][T[i]] -= fmin;
        }

        flow += fmin * D[U];
    }
    fout << flow;
}

int main() {
    read();
    minFlow();
}