Cod sursa(job #2907214)

Utilizator bluestorm57Vasile T bluestorm57 Data 29 mai 2022 12:44:52
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1005;
const int inf = 2e9;
int n,m;
int c[NMAX][NMAX], F[NMAX][NMAX], parent[NMAX];
bool viz[NMAX];
vector < int > v[NMAX];

int BFS(){
    deque < int > q;
    for(int i = 2 ; i <= n ; i++)
        viz[i] = 0;
    q.push_back(1);
    while(!q.empty()){
        int node = q.front();
        q.pop_front();

        if(node == n) continue;

        for(auto nxt: v[node]){
            if(c[node][nxt] == F[node][nxt] || viz[nxt]) continue;
            viz[nxt] = 1;
            q.push_back(nxt);
            parent[nxt] = node;
        }
    }
    return viz[n];
}

int main(){
    f >> n >> m;
    for(int i = 0 ; i < m ; i++){
        int x, y, z;
        f >> x >> y >> z;
        v[x].push_back(y);
        v[y].push_back(x);
        c[x][y] += z;
    }

    int flow = 0;
    do{
        for(auto it : v[n]){
            if(F[it][n] == c[it][n] || !viz[it])  continue;

            parent[n] = it;
            int fmin = inf;

            for(int node = n ; node != 1 ; node = parent[node])
                fmin = min(fmin, c[parent[node]][node] - F[parent[node]][node]);

            if(fmin == 0) continue;

            for(int node = n ; node != 1 ; node = parent[node]){
                F[parent[node]][node] += fmin;
                F[node][parent[node]] -= fmin;
            }

            flow += fmin;
        }
    }while(BFS());

    g << flow;


    return 0;
}