Cod sursa(job #2426413)

Utilizator valentinoMoldovan Rares valentino Data 27 mai 2019 20:47:23
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <queue>

int rGraph[1001][1001];
std::vector< std::pair<int, int> > graph[1001];

bool BFS(int n, int s, int t, int parent[]){

    bool visited[1001];

    for(int i = 1; i <= n; ++i)
        visited[i] = 0;

    std::queue<int> q;
    q.push(s);
    visited[s] = true;
    parent[s] = -1;

    while (!q.empty()){

        int u = q.front();
        q.pop();

        for (auto& edge : graph[u]){
            int v = edge.first;
            if (!visited[v] && rGraph[u][v] > 0){
                q.push(v);
                parent[v] = u;
                visited[v] = true;
            }
        }
    }
    return visited[t];
}

int FordFulkerson(int n){

    int u, v;
    int parent[1000], maxFlow = 0;

    for(int i = 1; i <= n; ++i)
        for(auto edge : graph[i])
            rGraph[i][edge.first] = edge.second;

    while(BFS(n, 1, n, parent)){

        int pathFlow = (1 << 31) - 1;

        for(v = n; v != 1; v = parent[v]){
            u = parent[v];
            pathFlow = std::min(pathFlow, rGraph[u][v]);
        }

        for(v = n; v != 1; v = parent[v]){
            u = parent[v];
            rGraph[u][v] -= pathFlow;
            rGraph[v][u] += pathFlow;
        }
        maxFlow += pathFlow;
    }
    return maxFlow;
}

int main(){

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

    int n, m, x, y, c;

    f >> n >> m;
    while(m--){
        f >> x >> y >> c;
        graph[x].push_back({y, c});
    }

    g << FordFulkerson(n) << '\n';
}