Cod sursa(job #2884785)

Utilizator buzu.tudor67Tudor Buzu buzu.tudor67 Data 4 aprilie 2022 21:44:21
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <bits/stdc++.h>
using namespace std;

class Graph{
public:
    const int N;
    vector<vector<int>> neighbors;
    vector<vector<int>> capacity;

public:
    Graph(const int& N): N(N){
        neighbors.resize(N);
        capacity.assign(N, vector<int>(N));
    }

    void addEdge(int x, int y, int c){
        neighbors[x].push_back(y);
        neighbors[y].push_back(x);
        capacity[x][y] = c;
    }
};

class FordFulkerson{
private:
    const Graph& G;
    const int N;
    const int SRC;
    const int DEST;
    vector<vector<int>> f;
    vector<bool> vis;

    int augmentingPath(int node, int minDelta){
        if(vis[node]){
            return 0;
        }
        
        vis[node] = true;
        
        if(node == DEST){
            return minDelta;
        }

        for(int nextNode: G.neighbors[node]){
            int remainingCapacity = G.capacity[node][nextNode] - f[node][nextNode];
            if(remainingCapacity > 0){
                int delta = augmentingPath(nextNode, min(minDelta, remainingCapacity));
                if(delta > 0){
                    f[node][nextNode] += delta;
                    f[nextNode][node] -= delta;
                    return delta;
                }
            }
        }

        return 0;
    }

public:
    FordFulkerson(const Graph& G, const int& SRC, const int& DEST):
                  G(G), N(G.N), SRC(SRC), DEST(DEST){
    }

    int computeMaxFlow(){
        f.assign(N, vector<int>(N, 0));
        vis.assign(N, false);

        int maxFlow = 0;
        bool containsAugmentingPath = true;
        while(containsAugmentingPath){
            fill(vis.begin(), vis.end(), false);
            int delta = augmentingPath(SRC, INT_MAX);
            if(delta > 0){
                maxFlow += delta;
            }else{
                containsAugmentingPath = false;
            }
        }
        
        return maxFlow;
    }
};

int main(){
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");

    int N, M;
    cin >> N >> M;

    Graph G(N);
    int x, y, c;
    for(int i = 0; i < M; ++i){
        cin >> x >> y >> c;
        G.addEdge(x - 1, y - 1, c);
    }

    cout << FordFulkerson(G, 0, N - 1).computeMaxFlow();

    cin.close();
    cout.close();
    return 0;
}