Cod sursa(job #2952489)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 9 decembrie 2022 13:30:02
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.47 kb
#include <bits/stdc++.h>

using namespace std;

class FlowGraph {
    int source, sink, n;
    vector <vector <int>> adj;
    vector <vector <int>> cap;
    vector <int> parent;
    vector <bool> vis;

    bool bfs() {
        fill(vis.begin(), vis.end(), false);
        vis[source] = true;

        queue <int> q;
        q.push(source);

        while (!q.empty()) {
            int node = q.front();
            q.pop();
            if (node == sink)
                continue;

            for (int nei : adj[node]) 
                if (!vis[nei] and cap[node][nei]) {
                    vis[nei] = true;
                    parent[nei] = node;
                    q.push(nei);
                }
        }

        return vis[sink];
    }
    
public:
    FlowGraph(int N, int v_source = -1, int v_sink = -1) {
        n = N;
        if (v_source == -1 and v_sink == -1) {
            v_source = n + 1;
            v_sink = n + 2;
            n += 2;
        }
        source = v_source;
        sink = v_sink;

        adj.resize(n + 5);
        cap.resize(n + 5);
        parent.resize(n + 5, -1);
        vis.resize(n + 5);
        for (auto& line : cap)
            line.resize(n + 5, 0);
    }

    void add_edge(int from, int to, int c) {
        cap[from][to] = c;
        adj[to].push_back(from);
        adj[from].push_back(to);
    }

    void link_to_source(int node, int c) {
        add_edge(source, node, c);
    }

    void link_to_sink(int node, int c) {
        add_edge(node, sink, c);
    }

    int max_flow() {
        int max_flow = 0;

        while (bfs()) {
            for (int node : adj[sink])
                if (vis[node] and cap[node][sink]) {
                    parent[sink] = node;
                    int flow = INT_MAX;
                    
                    for (int x = sink; x != source; x = parent[x])
                        flow = min(flow, cap[parent[x]][x]);

                    for (int x = sink; x != source; x = parent[x]) {
                        cap[parent[x]][x] -= flow;
                        cap[x][parent[x]] += flow;
                    }

                    max_flow += flow;
                }
        }

        return max_flow;
    }
};

int main() {
    string filename = "maxflow";
    ifstream cin(filename + ".in");
    ofstream cout(filename + ".out");

    int n, m;
    cin >> n >> m;
    FlowGraph G(n, 1, n);

    while (m--) {
        int x, y, z;
        cin >> x >> y >> z;
        G.add_edge(x, y, z);
    }

    cout << G.max_flow();

    return 0;
}