Cod sursa(job #2918020)

Utilizator NuSuntRomanIspir Alexandru NuSuntRoman Data 9 august 2022 12:40:05
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
/**
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,fma,sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native")
**/

#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>

/**
std :: ifstream fin("t.in");
std :: ofstream fout("t.out");
**/

const int mod = 1e9 + 7;
long long n, m, flow, capacity[505][505], t[505], f[505], layer[505];

bool BFS(int node) {
    std :: queue < int > Q;

    for (int i = 0; i < n; ++ i)
        layer[i] = -1;

    layer[node] = 0;
    Q.push(node);

    while (!Q.empty()) {
        int u = Q.front();

        for (int i = 0; i < n; ++ i)
            if (capacity[u][i] > 0 && layer[i] == -1) {
                Q.push(i);
                layer[i] = 1 + layer[u];
            }

        Q.pop();
    }

    return (layer[n - 1] != -1);
}

void DFSUtil(int node) {
    f[node] = true;

    for (int i = 0; i < n; ++ i)
        if (f[i] == false && capacity[node][i] > 0 && layer[node] == layer[i] - 1) {
            t[i] = node;
            DFSUtil(i);
        }

    return;
}

bool DFS(int node) {
    for (int i = 0; i < n; ++ i) {
        t[i] = -1;
        f[i] = false;
    }

    DFSUtil(node);

    return (t[n - 1] != -1);
}

int main() {
    std :: ios_base :: sync_with_stdio(false);
    std :: cin.tie(nullptr);

    std :: cin >> n >> m;

    for (int i = 0, u, v, c; i < m; ++ i) {
        std :: cin >> u >> v >> c;

        -- u, -- v;

        capacity[u][v] += c;
    }

    while (BFS(0)) {
        while (DFS(0)) {
            long long x = n - 1, Min = (1LL << 60);

            while (t[x] != -1) {
                Min = std :: min(Min, capacity[t[x]][x]);

                x = t[x];
            }

            x = n - 1;

            while (t[x] != -1) {
                capacity[t[x]][x] -= Min;
                capacity[x][t[x]] += Min;

                x = t[x];
            }

            flow += Min;
        }
    }

    std :: cout << flow;

    return 0;
}