Cod sursa(job #2902774)

Utilizator sichetpaulSichet Paul sichetpaul Data 16 mai 2022 19:53:33
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define Nmax 1002
using namespace std;

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

int N, M;
vector<int> G[Nmax];
int height[Nmax], cap[Nmax][Nmax], flow[Nmax][Nmax], overflow[Nmax];

int findVertex() {
    for (int i = 2; i < N; ++i)
        if (overflow[i] > 0) return i;
    return -1;
}

bool push(int u) {
    for (auto v: G[u])
        if (height[u] > height[v] && cap[u][v] - flow[u][v] > 0) {
            int pushFlow = min(overflow[u], cap[u][v] - flow[u][v]);
            //cout << u << " " << v << " " << " " << pushFlow << "\n";

            overflow[u] -= pushFlow;       /// fluxul se deplaseaza pe directia muchiei u -> v
            overflow[v] += pushFlow;

            flow[u][v] += pushFlow;
            flow[v][u] -= pushFlow;

            return true;
    }

    return false;
}

void relabel(int u) {
    int minHeight = N;
    for (auto v: G[u]) {
        if (flow[u][v] < cap[u][v])
            minHeight = min(minHeight, height[v]);
   }

    height[u] = minHeight + 1;
}

void preflowPush() {
    height[1] = N;
    for (auto v: G[1]) {
        flow[1][v] = overflow[v] = cap[1][v];
        flow[v][1] = -cap[1][v];
    }
}
int main()
{
    fin >> N >> M;
    while(M--) {
        int x, y, c;
        fin >> x >> y >> c;
        //++x, ++y;
        G[x].push_back(y);
        G[y].push_back(x);
        cap[x][y] = c;
    }

    preflowPush();

    while (findVertex() != -1) {
        int u = findVertex();
        if (!push(u)) relabel(u);
    }

    fout << overflow[N] << "\n";

    return 0;
}