Cod sursa(job #3261338)

Utilizator raizoSoare Antonio raizo Data 5 decembrie 2024 15:43:45
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <fstream>
#include <vector>
#include <deque>
#include <climits>
using namespace std;

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

int n, m, x, y, c;
struct edge {
    int capacity;
    int flow = 0;
    int residual;
    bool reverse;
};

void dfs(deque<int>& path, int& best_flow, vector<vector<edge>>& mat, vector<int>& visited, int flow = INT_MAX, int dest = n) {
    int current = path[path.size() - 1];
    if (current == dest) {
        best_flow = flow;
    }
    else if (current != dest) {
        for (int node = 1; node <= n; node++) {
            int possible_flow = min(flow, mat[current][node].residual);
            if (possible_flow > visited[node]) {
                visited[node] = possible_flow;
                path.push_back(node);
                dfs(path, best_flow, mat, visited, possible_flow);
                if (best_flow != 0) {
                    break;
                }
                path.pop_back();
            }
        }
    }
}


void update(edge& e, edge& r, int flow) {

    if (!e.reverse) {
        e.flow += flow;
        e.residual = e.capacity - e.flow;
        r.residual = e.flow;
    }
    else {
        edge& aux = e;
        e = r;
        r = aux;
        e.flow -= flow;
        e.residual = e.capacity - e.flow;
        r.residual = e.flow;
    }
}

int ford_fulkerson(vector<vector<edge>>& mat, int source = 1, int dest = n) {
    int max_flow = 0;
    while (true) {

        int flow = 0;
        deque<int> path;
        vector<int> visited(n + 1, 0);
        path.push_back(source);
        visited[source] = INT_MAX;
        dfs(path, flow, mat, visited);

        if (path.size() == 0 || path[path.size() - 1] != dest) {
            break;
        }

        for (int i = 0; i < path.size() - 1; i++) {
            x = path[i];
            y = path[i + 1];
            update(mat[x][y], mat[y][x], flow);
        }

        max_flow += flow;
    }
    return max_flow;
}


int main()
{
    cin >> n >> m;
    vector<edge> v(n + 1, {0,0});
    vector<vector<edge>> mat(n + 1, v);
    for (int i = 0; i < m; i++) {
        cin >> x >> y >> c;
        mat[x][y] = { c,0,c,0 };
        mat[y][x] = { 0,0,0,1 };
    }

    int result = ford_fulkerson(mat);

    cout << result << endl;
}