Cod sursa(job #1141039)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 12 martie 2014 15:27:35
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.58 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[] = "maxflow.in";
const char outfile[] = "maxflow.out";

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

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

typedef vector<int> Graph[MAXN];
typedef vector<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; }

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

inline bool BFs(int Source, int Sink) {
    Used.reset();
    Q.push(Source);
    Used[Source] = 1;
    while(!Q.empty()) {
        int Node = Q.front();
        Q.pop();
        if(Node == Sink)
            continue;
        for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it) {
            if(!Used[*it] && C[Node][*it] - F[Node][*it] > 0) {
                Used[*it] = true;
                Q.push(*it);
                Father[*it] = Node;
            }
        }
    }
    return Used[Sink];
}

void doMaxFlow() {
    int maxFlow = 0;
    while(BFs(Source, Sink)) {
        for(It it = G[Sink].begin(), fin = G[Sink].end(); it != fin ; ++ it) {
            if(!Used[*it] || C[*it][Sink] - F[*it][Sink] <= 0)
                continue;
            Father[Sink] = *it;
            int bottleNeck = oo;
            for(int i = Sink ; i != Source ; i = Father[i])
                bottleNeck = min(bottleNeck, C[Father[i]][i] - F[Father[i]][i]);
            if(!bottleNeck)
                continue;
            for(int i = Sink ; i != Source ; i = Father[i]) {
                F[Father[i]][i] += bottleNeck;
                F[i][Father[i]] -= bottleNeck;
            }
            maxFlow += bottleNeck;
        }
    }
    fout << maxFlow << '\n';
}

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