Cod sursa(job #2821654)

Utilizator DordeDorde Matei Dorde Data 22 decembrie 2021 20:43:56
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int const N = 1001 , inf = (1 << 30);
int cap[N][N] , f[N][N] , h[N] , viz[N] , n , m , maxflow;
vector<int> v[N];
bool bfs(){
    fill(h , h + n + 1 , 0);
    queue<int> q;
    q.push(1);
    h[1] = 1;
    while(!q.empty()){
        int x = q.front();
        q.pop();
        for(int &y : v[x]){
            if(!h[y] && cap[x][y] - f[x][y] > 0){
                h[y] = 1 + h[x];
                q.push(y);
            }
        }
    }
    return h[n] != 0;
}
int dfs(int node , int ans){
    if(node == n)
        return ans;
    for(int &y : v[node]){
        if(h[node] + 1 == h[y] && cap[node][y] - f[node][y] > 0){
            int flow = dfs(y , min(ans , cap[node][y] - f[node][y]));
            if(flow > 0){
                f[node][y] += flow;
                f[y][node] -= flow;
                return flow;
            }
        }
    }
    return 0;
}
int main()
{
    fin >> n >> m;
    for(int i = 1 ; i <= m ; ++ i){
        int a , b , c;
        fin >> a >> b >> c;
        cap[a][b] = c;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    while(bfs()){
        int flow = dfs(1 , inf);
        while(flow > 0){
            maxflow += flow;
            flow = dfs(1 , inf);
        }
    }
    fout << maxflow << '\n';
    return 0;
}