Cod sursa(job #2684009)

Utilizator Constantin.Dragancea Constantin Constantin. Data 12 decembrie 2020 13:38:50
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;

struct Graph{
    int n, src, dst;
    vector < vector <int> > graph;
    vector <bool> vis;
    vector < vector <int> > cap;
    vector <int> pr;
    
    Graph(int _n, int _src, int _dst): n(_n), src(_src), dst(_dst),
        graph(n), vis(n), cap(n, vector<int>(n)), pr(n) { }
    
    void AddEdge(int a, int b, int c = 1){
        graph[a].push_back(b);
        graph[b].push_back(a);
        cap[a][b] += c;
        //cap[b][a] = 1;
    }
    
    bool bfs(){
        fill(vis.begin(), vis.end(), 0);
        vis[src] = 1;
        queue <int> Q;
        Q.push(src);
        while(!Q.empty()){
            int node = Q.front();
            Q.pop();
            if (node == dst)
                continue;
            for (auto it: graph[node]){
                if (vis[it] || !cap[node][it])
                    continue;
                pr[it] = node;
                vis[it] = 1;
                Q.push(it);                
            }
        }
        
        
        return vis[dst];
    }
    
    int MaxFlow() {
        int maxflow = 0;
        while (bfs()){
            for (auto it: graph[dst]){
                if (!vis[it] || !cap[it][dst])
                    continue;
                pr[dst] = it;
                int flow = 1e9;
                for (int node = dst; node != src; node = pr[node])
                    flow = min(flow, cap[pr[node]][node]);
                for (int node = dst; node != src; node = pr[node]){
                    cap[pr[node]][node] -= flow;
                    cap[node][pr[node]] += flow;
                }
                maxflow += flow;
            }
        }
        
        return maxflow;
    }
};

int main(){
    ifstream cin ("maxflow.in");
    ofstream cout("maxflow.out");
    
    int n, m;
    cin >> n >> m;
    Graph G(n, 0, n - 1);
    
    while (m--){
        int a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        G.AddEdge(a, b, c);
    }
    cout << G.MaxFlow() << '\n';
    return 0;
}