Cod sursa(job #3189342)

Utilizator annna7Pecheanu Anna annna7 Data 4 ianuarie 2024 21:17:53
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

#define NMAX 1000

using namespace std;

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

int V, E;
vector<bool> vis;
vector<int> parent;
vector<int> adj[NMAX];
vector<vector<int>> capacity;

int getAugmentingPathBFS() {
    parent.assign(V, -1);
    vis.assign(V, false);
    queue<pair<int, int>> q;
    int currNode = 0, currMin = INT_MAX;

    // holds {node, current min}
    q.emplace(currNode, currMin);

    while (!q.empty()) {
        currNode = q.front().first;
        currMin = q.front().second;
        q.pop();

        for (auto &neighbor: adj[currNode]) {
            if (parent[neighbor] == -1 && capacity[currNode][neighbor] != 0) {
                currMin = min(currMin, capacity[currNode][neighbor]);
                parent[neighbor] = currNode;
                if (neighbor == V - 1) {
                    return currMin;
                }
                q.emplace(neighbor, currMin);
            }
        }
    }

    return 0;
}

int getMaxFlow() {
    int totalFlow = 0, newPathFlow;

    newPathFlow = getAugmentingPathBFS();
    while (newPathFlow) {
        totalFlow += newPathFlow;
        int currNode = V - 1;
        while (currNode != 0) {
            int ancestor = parent[currNode];
            capacity[ancestor][currNode] -= newPathFlow;
            capacity[currNode][ancestor] += newPathFlow;
            currNode = ancestor;
        }
        newPathFlow = getAugmentingPathBFS();
    }

    return totalFlow;
}

int main()
{
    fin >> V >> E;
    capacity.resize(V, vector<int>(V, 0));

    int x, y, w;
    for (int i = 0; i < E; ++i) {
        fin >> x >> y >> w;
        --x, --y;
        adj[x].push_back(y);
        adj[y].push_back(x);
        capacity[x][y] = w;
    }

    fout << getMaxFlow();

    return 0;
}