Cod sursa(job #2959105)

Utilizator DevCrutCorolevschi Mihai DevCrut Data 29 decembrie 2022 20:09:55
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 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<vector<int>> flowMap;
vector<int> parentMap;

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

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

    adjList.resize(n);
    capacityMap.resize(n, vector<int>(n));
    flowMap.resize(n, vector<int>(n));
    parentMap.resize(n, -1);
    parentMap[0] = INT_MAX;
    for (int i = 0; i < m; i++) {
        int x, y, f;
        myIn >> x >> y >> f; x--; y--;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
        capacityMap[x][y] = f;
        capacityMap[y][x] = 0;
    }
}

bool BFS() {
    fill(parentMap.begin(), parentMap.end(), -1);
    queue<int> q;
    q.push(0);

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

        for (int j = 0; j < adjList[currentNode].size(); j++) {
            int nextNode = adjList[currentNode][j];
            int flow = flowMap[currentNode][nextNode];
            int capacity = capacityMap[currentNode][nextNode];

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

                if (nextNode == (n - 1)) {
                    return true;
                }
            }
        }
    }

    return false;
}

void EdmondsKarp() {
    while (BFS() == true) {
        int minFlow = INT_MAX;
        int node = n - 1;
        do {
            int prevNode = parentMap[node];
            minFlow = min(minFlow, capacityMap[prevNode][node] - flowMap[prevNode][node]);
            node = prevNode;
        } while (node != 0);

        node = n - 1;
        do {
            int prevNode = parentMap[node];
            flowMap[node][prevNode] -= minFlow;
            flowMap[prevNode][node] += minFlow;
            node = prevNode;
        } while (node != 0);
        
        maxFlow += minFlow;
    }
}

void Output() {
    myOut << maxFlow;
    myOut.close();
    myIn.close();
}

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