Cod sursa(job #2207328)

Utilizator MaligMamaliga cu smantana Malig Data 25 mai 2018 15:27:58
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <bits/stdc++.h>

using namespace std;

#if 1
    #define pv(x) cout<<#x<<" = "<<(x)<<"; ";cout.flush()
    #define pn cout<<endl
#else
    #define pv(x)
    #define pn
#endif

#ifdef INFOARENA
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");
#else
    #define in cin
    #define out cout
#endif

using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
#define pb push_back
#define mp make_pair
const int NMax = 1e3 + 5;
const ll inf_ll = 1e18 + 5;
const int inf_int = 1e9 + 5;
const int mod = 100003;
using zint = int;

int cap[NMax][NMax], prv[NMax];
bool vis[NMax];
vector<int> adj[NMax];

bool bfs(int N) {
    memset(vis, 0, sizeof(vis));
    memset(prv, 0, sizeof(prv));

    queue<int> Q;
    Q.push(1);
    while (Q.size()) {
        int curr = Q.front(); Q.pop();

        if (curr == N) {
            return true;
        }

        for (int nxt : adj[curr]) {
            if (prv[nxt] || !cap[curr][nxt]) {
                continue;
            }

            prv[nxt] = curr;
            Q.push(nxt);
        }
    }

    return false;
}

int main() {
    cin.sync_with_stdio(false);
    cin.tie(0);

    int N, M;
    in >> N >> M;

    for (int i = 1;i <= M; ++i) {
        int x,y,c;
        in >> x >> y >> c;

        cap[x][y] += c;
        adj[x].pb(y);
        adj[y].pb(x);
    }

    int maxFlow = 0;
    while (bfs(N)) {
        for (int i = 2;i < N; ++i) {
            if (cap[i][N] == 0 || !prv[i]) {
                continue;
            }

            prv[N] = i;
            
            int node = N;
            int minFlow = inf_int;
            while (node != 1) {
                minFlow = min(minFlow, cap[prv[node]][node]);
                node = prv[node];
            }

            node = N;
            while (node != 1) {
                cap[prv[node]][node] -= minFlow;
                cap[node][prv[node]] += minFlow;
                node = prv[node];
            }

            maxFlow += minFlow;
        }
    }

    out << maxFlow << '\n';

    return 0;
}