Cod sursa(job #2901663)

Utilizator sichetpaulSichet Paul sichetpaul Data 14 mai 2022 09:11:11
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
#define Nmax 1002
#define INF 1e9
#define Mmax 5002
using namespace std;

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

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


void updateGraph(int newFlow) {
    int y = N;
    while (y != 1) {
        int x = t[y];
        flow[x][y] += newFlow;
        flow[y][x] -= newFlow;
        y = x;
    }
}

int BFS() {
    queue<int> Q;
    bool vis[Nmax];
    int Min[Nmax];
    memset(vis, false, sizeof(vis));
    memset(Min, 0, sizeof(Min));

    Q.push(1);
    vis[1] = true;
    Min[1] = INF;
    while (!Q.empty()) {
        int x = Q.front();
        Q.pop();

        for (auto y: G[x])
        if (!vis[y] && flow[x][y] < cap[x][y]) {
            vis[y] = true;
            t[y] = x;
            Min[y] = min(Min[x], cap[x][y] - flow[x][y]);
            Q.push(y);
            if (y == N) break;
        }
    }

    return Min[N];
}
int main()
{
    fin >> N >> M;
    while (M--) {
       int x, y, c;
       fin >> x >> y >> c;
       cap[x][y] = c;
       G[x].push_back(y);
    }

    int ans = 0;
    while (1) {
        int newFlow = BFS();
        if (newFlow == 0) break;
        ans += newFlow;
        updateGraph(newFlow);
    }

    fout << ans << '\n';

    return 0;
}