Cod sursa(job #2813494)

Utilizator bianca_voicuBianca Voicu bianca_voicu Data 6 decembrie 2021 20:19:49
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.4 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const int INF = 1 << 30;

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

class Graph {
private:
    int _n, _m;
    vector<vector<int>> _adjacentList; // liste de adiacenta

public:
    void setAdjacentList(const vector<vector<int>> &adjacentList);

    Graph(int nodes, int edges) : _n(nodes), _m(edges) {}

    bool bfsFlow();

    int maxFlow();
};

void Graph::setAdjacentList(const vector<vector<int>> &adjacentList) {
    _adjacentList = adjacentList;
}

int source, destination;
int capacity[1001][1001], flow[1001][1001], dad[1001];
queue<int> q;


bool Graph::bfsFlow() {
    for (int i = 1; i <= _n; i++) {
        dad[i] = 0;
    }

    q.push(source);
    dad[source] = source;

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

        if (currentNode == destination)
            return 1;

        for (auto &node : _adjacentList[currentNode]) {
            if ((capacity[currentNode][node] - flow[currentNode][node] > 0) && dad[node] == 0) {
                dad[node] = currentNode;
                q.push(node);
            }
        }
    }
    return 0;
}

int Graph::maxFlow() {
    int answer = 0;
    source = 1;
    destination = _n;

    while (bfsFlow()) {
        for (auto &node : _adjacentList[destination]) {
            int currentNode = destination;
            int minim = INF;

            dad[destination] = node;
            while (currentNode != source) {
                minim = min(minim, capacity[dad[currentNode]][currentNode] - flow[dad[currentNode]][currentNode]);
                currentNode = dad[currentNode];
            }

            currentNode = destination;
            while (currentNode != source) {
                flow[dad[currentNode]][currentNode] += minim;
                flow[currentNode][dad[currentNode]] -= minim;
                currentNode = dad[currentNode];
            }
            answer += minim;
        }
    }

    return answer;
}


int main() {
    int n, m, answer, x, y, z;
    f >> n >> m;
    Graph grf(n, m);
    vector<vector<int>> gr(100001);

    for (int i = 0; i < m; ++i) {
        f >> x >> y >> z;
        gr[x].push_back(y);
        gr[y].push_back(x);
        capacity[x][y] = z;
    }
    grf.setAdjacentList(gr);

    answer = grf.maxFlow();
    g << answer;

    f.close();
    g.close();
    return 0;
}