Cod sursa(job #2247065)

Utilizator circeanubogdanCirceanu Bogdan circeanubogdan Data 27 septembrie 2018 20:59:34
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#define DIM 1002

using namespace std;

ifstream in ("maxflow.in");
ofstream out("maxflow.out");

int nodeNum, edgeNum, maxFlow;
int capacity[DIM][DIM], flow[DIM][DIM], father[DIM];

vector<int> graph[DIM];

bool visited[DIM];

queue<int> nodeQueue;

void reset(bool v[]){
    for(int cnt = 1; cnt <= nodeNum; ++ cnt)
        v[cnt] = false;
}

bool bfs(){
    reset(visited);
    nodeQueue.push(1);
    visited[1] = true;
    while(!nodeQueue.empty()){
        int currentNode = nodeQueue.front();
        for(auto nextNode : graph[currentNode]){
            if(!visited[nextNode] && capacity[currentNode][nextNode] - flow[currentNode][nextNode] > 0){
                visited[nextNode] = true;
                nodeQueue.push(nextNode);
                father[nextNode] = currentNode;
            }
        }
        nodeQueue.pop();
    }
    return visited[nodeNum];
}

int main()
{
    in>>nodeNum>>edgeNum;
    for(int edgeCnt = 1; edgeCnt <= edgeNum; ++ edgeCnt){
        int node1, node2;
        in>>node1>>node2;
        in>>capacity[node1][node2];
        graph[node1].push_back(node2);
        graph[node2].push_back(node1);
    }
    
    while(bfs() == true){
        
        for(auto nodeCnt : graph[nodeNum]){
            if(capacity[nodeCnt][nodeNum] - flow[nodeCnt][nodeNum] <= 0 || !visited[nodeCnt])
                continue;
            int minFlow = capacity[nodeCnt][nodeNum] - flow[nodeCnt][nodeNum];
            int currentNode = nodeCnt;
            while(currentNode != 1){
                minFlow = min(minFlow, capacity[father[currentNode]][currentNode] - flow[father[currentNode]][currentNode]);
                currentNode = father[currentNode];
            }
            currentNode = nodeCnt;
            flow[currentNode][nodeNum] += minFlow;
            flow[nodeNum][currentNode] -= minFlow;
            maxFlow += minFlow;
            while(currentNode != 1){
                flow[father[currentNode]][currentNode] += minFlow;
                flow[currentNode][father[currentNode]] -= minFlow;
                currentNode = father[currentNode];
            }
            
        }
    }
    
    out<<maxFlow;
    
    
    return 0;
}