Cod sursa(job #2955906)

Utilizator SteanfaDiaconu Stefan Steanfa Data 18 decembrie 2022 11:00:01
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <utility>
#include <queue>
#include <unordered_map>

const int magic = 1001;
std::vector<std::unordered_map<int, int>> v(magic);

int bfsBottleneck(std::vector<std::unordered_map<int, int>> &v, int n)
{
    std::queue<int> q;
    std::vector<std::pair<int, int>> generator(magic, {0, 0});
    std::vector<bool> mark(magic, 0);
    q.push(1);
    mark[1] = 1;

    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        if (nod == n)
        {
            int min = 110'002;
            int NOD = nod;
            while (generator[NOD].first != 0)
            {
                min = std::min(min, generator[NOD].second);
                NOD = generator[NOD].first;
            }

            while (generator[nod].first != 0)
            {
                v[generator[nod].first][nod] -= min;
                v[nod][generator[nod].first] += min;
                nod = generator[nod].first;
            }
            return min;
        }

        for (auto &&nbh : v[nod])
        {
            if (nbh.second != 0 and mark[nbh.first] == 0)
            {
                mark[nbh.first] = 1;
                generator[nbh.first].first = nod;
                generator[nbh.first].second = nbh.second;
                q.push(nbh.first);
            }
        }
    }
    return -1;
}

int main()
{
    std::ifstream cin("maxflow.in");
    std::ofstream cout("maxflow.out");
    short n, m;
    cin >> n >> m;
    int x, y, cap;
    for (size_t i = 0; i < m; i++)
    {
        cin >> x >> y >> cap;
        v[x][y] = cap;
    }

    int fluxPlus, total = 0;
    while (1)
    {
        fluxPlus = bfsBottleneck(v, n);
        if (fluxPlus < 0)
        {
            break;
        }
        total += fluxPlus;
    }
    cout << total;
}