Cod sursa(job #3270909)

Utilizator BogdancxTrifan Bogdan Bogdancx Data 24 ianuarie 2025 20:47:07
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

int find_augmenting(vector<vector<int>>& residual, vector<int>& parent, int start, int end) 
{
    fill(parent.begin(), parent.end(), -1);
    queue<pair<int, int>> q;

    q.emplace(start, 1e9);

    while (!q.empty()) {
        int node = q.front().first;
        int crt_flow = q.front().second;
        q.pop();

        for (int neighbor = 1; neighbor <= residual.size() - 1; neighbor++) 
        {
            if (parent[neighbor] == -1 && residual[node][neighbor] > 0) 
            {
                parent[neighbor] = node;
                int new_flow = min(crt_flow, residual[node][neighbor]);
                if (neighbor == end) 
                {
                    return new_flow;
                }
                q.emplace(neighbor, new_flow);
            }
        }
    }

    return 0;
}

int maxflow(vector<vector<int>> graph) {
    int start = 1, end = graph.size() - 1;

    vector<int> parent(graph.size());
    vector<vector<int>> residual = graph;
    int flow = 0;

    int aug;
    while ((aug = find_augmenting(residual, parent, start, end)) != 0) {
        flow += aug;

        int t = end;
        while (t != start) {
            int prev = parent[t];
            residual[prev][t] -= aug;
            residual[t][prev] += aug;
            t = prev;
        }
    }

    return flow;
}

int main() 
{
    int n, m;
    ifstream fin("minflow.in");
    ofstream fout("maxflow.out");

    fin >> n >> m;

    vector<vector<int>> graph(n + 1, vector<int>(n + 1, 0));

    for (int i = 0; i < m; i++) {
        int a, b, c;
        fin >> a >> b >> c;

        graph[a][b] += c;
    }

    fout << maxflow(graph);

    return 0;
}