Cod sursa(job #2961346)

Utilizator cyg_vladioanBirsan Vlad cyg_vladioan Data 6 ianuarie 2023 11:47:04
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <climits>

const int INF = INT_MAX;

class MaxFlow{
private:
    int n, s, d;
    std::vector<std::vector<int>> cap_flow;
    std::vector<std::vector<int>> G;
    std::vector<int> t;

public:
    MaxFlow(int, int, int, std::vector<std::pair <int, std::pair<int, int>>>&);
    int bfs();
    int update_flow();
    int max_flow(); 
};

MaxFlow::MaxFlow(int n, int s, int d, std::vector<std::pair <int, std::pair<int, int>>>& edges): n(n), s(s), d(d){
    cap_flow = std::vector<std::vector<int>> (n, std::vector<int>(n, 0));
    G = std::vector<std::vector<int>>(n);

    for(const auto& edge: edges){
        G[edge.first].push_back(edge.second.first);
        G[edge.second.first].push_back(edge.first);
        cap_flow[edge.first][edge.second.first] = edge.second.second;
    }
}

int MaxFlow::bfs(){
    std::queue<int> q;

    t = std::vector<int> (n, -1);
    t[s] = -2;
    q.push(s);

    while(!q.empty()){
        int u = q.front();
        q.pop();
        if(u == d)
            continue;
        for(const auto& v: G[u])
            if(t[v] == -1 && cap_flow[u][v] > 0){
                t[v] = u;
                q.push(v);
            }
    }

    return t[d] != -1;
}

int MaxFlow::update_flow(){
    int node, flow;
    flow = INF;
    
    for(node = d; t[node] != -2; node = t[node])
        flow = std::min(flow, cap_flow[t[node]][node]);
    
    for(node = d; t[node] != -2; node = t[node]){
        cap_flow[t[node]][node] -= flow;
        cap_flow[node][t[node]] += flow;
    }

    return flow;
}

int MaxFlow::max_flow(){
    int flow = 0;
    
    while(bfs()){
        for(const auto& node: G[d]){
            if(t[node] == -1 || cap_flow[node][d] == 0)
                continue;
            t[d] = node;
            flow += update_flow();
        }
    }

    return flow;
}

int main(){
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    int n, m, i, x, y, z;
    std::vector<std::pair <int, std::pair<int, int>>> edges;

    scanf("%d%d", &n, &m);
    for(int i = 0; i < m; i ++){
        scanf("%d%d%d", &x, &y, &z);
        edges.push_back({x - 1, {y - 1, z}});
    }

    MaxFlow maxflow(n, 0, n - 1, edges);
    int max_flow = maxflow.max_flow();

    printf("%d\n", max_flow);

    return 0;
}