Cod sursa(job #2963187)

Utilizator DannyBroUngureanu Dan-Andrei DannyBro Data 10 ianuarie 2023 11:31:42
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int MAXN = 1005;
const int INF = 0x3f3f3f3f;

int n, m;
int graph[MAXN][MAXN];
int parent[MAXN];

int max_flow(int sursa, int destinatie) {
    int flow = 0;
    while (true) {
        // Find an augmenting path using BFS
        memset(parent, -1, sizeof parent);
        parent[sursa] = -2;
        queue<int> q;
        q.push(sursa);
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            for (int v = 0; v < n; v++) {
                if (parent[v] == -1 && graph[u][v] > 0) {
                    parent[v] = u;
                    q.push(v);
                    if (v == destinatie) {
                        goto out_of_while;
                    }
                }
            }
        }
        out_of_while:
        // If we couldn't find an augmenting path, we're done
        if (parent[destinatie] == -1) {
            break;
        }
        // Find the minimum flow along the augmenting path
        int min_flow = INF;
        for (int v = destinatie; v != sursa; v = parent[v]) {
            int u = parent[v];
            min_flow = min(min_flow, graph[u][v]);
        }
        // Update the flow and the residual graph
        for (int v = destinatie; v != sursa; v = parent[v]) {
            int u = parent[v];
            graph[u][v] -= min_flow;
            graph[v][u] += min_flow;
        }
        flow += min_flow;
    }
    return flow;
}

int main() {

    fin >> n >> m;

    // Initializam matricea cu 0
    memset(graph, 0, sizeof graph);
    // Read in the edges
    for (int i = 0; i < m; i++) {
        int u, v, c;
        fin >> u >> v >> c;
        graph[u][v] += c; // for multiple edges
    }

    int sursa = 1, destinatie = n;

    // Print the maximum flow
    fout << max_flow(sursa, destinatie) << endl;
    return 0;
}