Cod sursa(job #2749078)

Utilizator codruta.miron08Miron Ioana Codruta codruta.miron08 Data 4 mai 2021 21:38:14
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <bits/stdc++.h>
#define pb push_back
#include <fstream>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int MAXN = 1e4;

vector<int> graph[MAXN];
int cap[MAXN][MAXN], fl[MAXN][MAXN], par[MAXN];

void dfs(int node, int parent, int dest, bool &found) {
    par[node] = parent;

    if (node == dest) {
        found = true;
        return;
    }

    for (const auto& it: graph[node])
        if (par[it] == -1 && cap[node][it] > fl[node][it]) {
            dfs(it, node, dest, found);
            if (found)
                return;
        }
}

bool isPath(int source, int dest) {
    bool found = false;
    memset(par, -1, sizeof(par));
    dfs(source, source, dest, found);

    return par[dest] != -1;
}

int getMinFlow(int dest) {
    int node = dest, flow = INT_MAX;

    while (node != par[node]) {
        flow = min(flow, cap[par[node]][node] - fl[par[node]][node]);
        node = par[node];
    }

    return flow;
}

void updatePath(int dest, int flow) {
    int node = dest;

    while (node != par[node]) {
        fl[par[node]][node] += flow;
        node = par[node];
    }
}

int getFlow(int source, int dest) {
    int maxFlow = 0;
    memset(fl, 0, sizeof(fl));

    while (isPath(source, dest)) {
        int flow = getMinFlow(dest);
        maxFlow += flow;
        updatePath(dest, flow);
    }

    return maxFlow;
}

void read(int& source, int& dest) {

    int n, m;

    fin >> n >> m;
   source = 1;
   dest = n;
    for (int i = 0; i < m; ++i) {
        int x, y, c;

        fin >> x >> y >> c;
        graph[x].pb(y);
        graph[y].pb(x);
        cap[x][y] = cap[y][x] = c;
    }


}

int main() {
    int source, dest;
    read(source, dest);
    fout << getFlow(source, dest);

    return 0;
}