Cod sursa(job #2102537)

Utilizator DawlauAndrei Blahovici Dawlau Data 8 ianuarie 2018 23:27:24
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
#include<fstream>
#include<list>
#include<bitset>
#include<deque>
#include<climits>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1005, INF = INT_MAX;
int capacity[NMAX][NMAX], flow[NMAX][NMAX], BFStree[NMAX], nodes, edges;
bitset<NMAX> visited;
list<int> graph[NMAX];

inline void read_data(){

    fin >> nodes >> edges;

    int from, to, c;
    while(edges--){

        fin >> from >> to >> c;
        graph[from].push_back(to);
        graph[to].push_back(from);
        capacity[from][to] = c;
    }
}

inline bool BFS(){

    deque<int> queueForBFS;
    visited.reset();

    queueForBFS.push_back(1);
    visited[1] = true;

    list<int>::iterator it;
    int node;

    while(!queueForBFS.empty()){

        node = queueForBFS.front();
        queueForBFS.pop_front();

        if(node == nodes)
            queueForBFS.clear();
        else{
            for(it = graph[node].begin(); it != graph[node].end(); ++it)
                if(!visited[*it] and capacity[node][*it] != flow[node][*it]){

                    visited[*it] = true;
                    queueForBFS.push_back(*it);
                    BFStree[*it] = node;
                }
        }
    }

    return visited[nodes];
}

inline int getMinimumCapacity(){

    int node, minimumCapacity = INF;
    for(node = nodes; node != 1; node = BFStree[node])
        minimumCapacity = min(minimumCapacity, capacity[BFStree[node]][node] - flow[BFStree[node]][node]);

    return minimumCapacity;
}

inline void changeCapacities(int minimumCapacity){

    int node;
    for(node = nodes; node != 1; node = BFStree[node]){

        flow[BFStree[node]][node] += minimumCapacity;
        flow[node][BFStree[node]] -= minimumCapacity;
    }
}

inline int getMaxFlow(){

    int maxFlow = 0, minimumCapacity;
    list<int>::iterator it;

    while(BFS())
        for(it = graph[nodes].begin(); it != graph[nodes].end(); ++it)
            if(capacity[*it][nodes] != flow[*it][nodes] and visited[*it]){

                BFStree[nodes] = *it;
                minimumCapacity = getMinimumCapacity();
                changeCapacities(minimumCapacity);
                maxFlow += minimumCapacity;
            }

    return maxFlow;
}

int main(){
    read_data();
    fout << getMaxFlow();
}