Cod sursa(job #2959158)

Utilizator DevCrutCorolevschi Mihai DevCrut Data 29 decembrie 2022 22:14:26
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <vector>
#include <iostream>
#include <string.h>
#include <string>
#include <sstream>
#include <climits>
#include <queue>

using namespace std;

int n, m, maxFlow;
vector<vector<int>> adjList;
vector<vector<int>> capacityMap;
vector<int> parentMap;

const int start = 1;
int finish;

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

void ReadInputs() {
    myIn >> n >> m;

    finish = start + n - 1;

    adjList.resize(finish + 1);
    capacityMap.resize(finish + 1, vector<int>(finish + 1));
    parentMap.resize(finish + 1, start - 1);

    int x, y, f;
    for (int i = 0; i < m; i++) {
        myIn >> x >> y >> f;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
        capacityMap[x][y] = f;
    }
}

bool BFS() {
    fill(parentMap.begin(), parentMap.end(), start - 1); //optimize? memset maybe?
    queue<int> q; //expensive!!!
    q.push(start);

    while (not q.empty()) {
        int currentNode = q.front();
        q.pop();

        if (currentNode == finish) {
            return true;
        }

        for (const auto& nextNode : adjList[currentNode]) {
            int capacity = capacityMap[currentNode][nextNode];

            if ((parentMap[nextNode] == (start - 1)) && (capacity > 0)) {
                q.push(nextNode);
                parentMap[nextNode] = currentNode;
            }
        }
    }
    return false;
}

void EdmondsKarp() {
    while (BFS()) {
        int minFlow = INT_MAX;
        for (int node = finish; node != start; node = parentMap[node]) {
            int prevNode = parentMap[node];
            minFlow = min(minFlow, capacityMap[prevNode][node]);
        }

        for (int node = finish; node != start; node = parentMap[node]) {
            int prevNode = parentMap[node];
            capacityMap[node][prevNode] += minFlow;
            capacityMap[prevNode][node] -= minFlow;
        }
        
        maxFlow += minFlow;
    }
}

void Output() {
    myOut << maxFlow;
}

int main() {
    ReadInputs();
    EdmondsKarp();
    Output();
}