Cod sursa(job #2961694)

Utilizator JovialJokerFlorea George JovialJoker Data 6 ianuarie 2023 21:09:34
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.51 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
const int NMAX = 1005;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int n, m;

vector<vector<int>> adj;
int flux[NMAX][NMAX];
bool visited[NMAX];
int pred[NMAX];
int total;

bool bfs() {
    queue<int> q;

    // Initialize all nodes as not visited and no predecessor
    for (int i = 1; i <= n; i++) {
        pred[i] = 0;
        visited[i] = false;
    }

    // Mark the source as visited and add it to the queue
    visited[1] = true;
    q.push(1);

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (auto& neighbor : adj[node]) {
            // If neighbor is not visited and there is residual capacity
            // in the edge (node, neighbor), visit it
            if (!visited[neighbor] && flux[node][neighbor] > 0) {
                pred[neighbor] = node;
                q.push(neighbor);
                visited[neighbor] = true;

                // If we reach the sink, return true
                if (neighbor == n)
                    return true;
            }
        }
    }
    // If we can't reach the sink, return false
    return false;
}

int main() {
    fin >> n >> m;
    adj.resize(n + 1);

    // Read the edges and add them to the adjacency list
    for (int i = 1; i <= m; i++) {
        int x, y, z;
        fin >> x >> y >> z;
        adj[x].push_back(y);
        adj[y].push_back(x);
        flux[x][y] = z;
    }

    // While there is a path from source to sink
    while (bfs()) {
        // For each neighbor of the sink
        for (auto& neighbor : adj[n]) {
            // If the neighbor is not visited, skip it
            if (!visited[neighbor])
                continue;

            // Find the minimum flow through the path from source to sink
            int min_flow = INT32_MAX;
            int node = n;
            while (node != 1) {
                min_flow = min(min_flow, flux[pred[node]][node]);
                node = pred[node];
            }

            // Decrease the residual capacity of the edges in the path
            // and increase the residual capacity of the reverse edges
            node = n;
            while (node != 1) {
                flux[pred[node]][node] -= min_flow;
                flux[node][pred[node]] += min_flow;
                node = pred[node];
            }

            // Add the minimum flow to the total flow
            total += min_flow;
        }
    }

    // Output the total flow
    fout << total;

    return 0;
}