Cod sursa(job #2918027)

Utilizator NuSuntRomanIspir Alexandru NuSuntRoman Data 9 august 2022 12:54:54
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 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("maxflow.in");
std :: ofstream fout("maxflow.out");


const int mod = 1e9 + 7;
int n, m, flow, capacity[1005][1005], t[1005], f[1005], ptr[1005], layer[1005];
bool ok;

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) {
    if (node == n - 1) {
        ok = true;
        return;
    }
    else {
        if (ok == false) {
            f[node] = true;

            for (int &i = ptr[node]; 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;
    }

    ok = false;
    DFSUtil(node);

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

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

    fin >> n >> m;

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

        -- u, -- v;

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

    while (BFS(0)) {
        for (int i = 0; i < n; ++ i)
            ptr[i] = 0;

        while (DFS(0)) {
            int x = n - 1, Min = (1 << 30);

            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;
        }
    }

    fout << flow;

    return 0;
}