Cod sursa(job #1160610)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 30 martie 2014 17:47:39
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.61 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "fmcm.in";
const char outfile[] = "fmcm.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 355;
const int oo = 0x3f3f3f3f;

typedef vector<pair<int, int> > Graph[MAXN];
typedef vector<pair<int, int> > :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

Graph G;
int C[MAXN][MAXN], N, M, Source, Sink, Father[MAXN], dp[MAXN];
bitset <MAXN> inQ;
queue <int> Q;

inline bool BF(Graph &G, int Source, int Sink) {
    Q.push(Source);
    inQ[Source] = 1;
    memset(dp, oo, sizeof(dp));
    dp[Source] = 0;
    while(!Q.empty()) {
        int Node = Q.front();
        Q.pop();
        inQ[Node] = 0;
        for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it)
            if(C[Node][it->first] > 0 && dp[it->first] > dp[Node] + it->second) {
                dp[it->first] = dp[Node] + it->second;
                Father[it->first] = Node;
                if(inQ[it->first])
                    continue;
                Q.push(it->first);
                inQ[it->first] = 1;
            }
    }
    return dp[Sink] != oo;
}

inline int getMinCostMaxFlow(Graph &G, int Source, int Sink) {
    int minCostMaxFlow = 0;
    while(BF(G, Source, Sink)) {
        int bottleNeck = oo;
        for(int i = Sink ; i != Source ; i = Father[i])
            bottleNeck = min(bottleNeck, C[Father[i]][i]);
        if(!bottleNeck)
            continue;
        for(int i = Sink ; i != Source ; i = Father[i]) {
            C[Father[i]][i] -= bottleNeck;
            C[i][Father[i]] += bottleNeck;
        }
        minCostMaxFlow += bottleNeck * dp[Sink];
    }
    return minCostMaxFlow;
}

int main() {
    fin >> N >> M >> Source >> Sink;
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y, z, c;
        fin >> x >> y >> z >> c;
        G[x].push_back(make_pair(y, c));
        G[y].push_back(make_pair(x,-c));
        C[x][y] = z;
    }
    fout << getMinCostMaxFlow(G, Source, Sink) << '\n';
    fin.close();
    fout.close();
    return 0;
}