Cod sursa(job #2897210)

Utilizator lucametehauDart Monkey lucametehau Data 2 mai 2022 22:04:07
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.73 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <cstring>
#include <chrono>
#include <cassert>
#include <bitset>
#include <stack>
#include <queue>
#include <iomanip>
#include <random>

#ifdef _MSC_VER
#  include <intrin.h>
#  define __builtin_popcount __popcnt
#  define __builtin_popcountll __popcnt64
#endif

//#pragma GCC optimize("Ofast")
#pragma GCC optimize("Ofast,unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define x first
#define y second
#define ld long double
#define ll long long
#define ull unsigned long long
#define us unsigned short
#define lsb(x) ((x) & (-(x)))
#define pii pair <int, int>
#define pll pair <ll, ll>

using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

mt19937 gen(time(0));
uniform_int_distribution <uint32_t> rng;

const int MOD = (int)1e9 + 7;

ll gcd(ll a, ll b) {
    if (!b)
        return a;
    return gcd(b, a % b);
}

int n, m, x, y, z;

int r[1005][1005];
int lst[1005];
vector <int> g[1005];

int bfs(int s, int t) {
    queue <int> q;

    for (int i = 1; i <= n; i++)
        lst[i] = 0;
    q.push(s);

    lst[1] = -1;

    while (!q.empty()) {
        int nod = q.front();

        q.pop();

        if (nod == t)
            return 1;

        for (auto& fiu : g[nod]) {
            if (r[nod][fiu] && !lst[fiu]) {
                lst[fiu] = nod;

                q.push(fiu);
            }
        }
    }

    return 0;
}

int max_flow(int s, int t) {
    int f, flow = 0;

    while(bfs(s, t)) {
        for (auto& fiu : g[t]) {
            int nod = t;

            if (!r[fiu][nod] || !lst[fiu])
                continue;

            lst[nod] = fiu;
            int f = (int)1e9;
            while (nod != s)
                f = min(f, r[lst[nod]][nod]), nod = lst[nod];

            nod = t;

            while (nod != s) {
                r[lst[nod]][nod] -= f;
                r[nod][lst[nod]] += f;
                nod = lst[nod];
            }

            flow += f;
        }

    }

    return flow;
}

void solve() {
    ld t1 = clock();
    in >> n >> m;

    for (; m; m--) {
        in >> x >> y >> z;
        r[x][y] += z;

        g[x].push_back(y);
        g[y].push_back(x);
    }

    out << max_flow(1, n) << "\n";

    ld t2 = clock();

    //out << (t2 - t1) / CLOCKS_PER_SEC << "s\n";
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    srand(time(0));

    int T = 1;

    //cin >> T;

    while (T--) {
        solve();
    }

    return 0;
}