Cod sursa(job #2821674)

Utilizator DordeDorde Matei Dorde Data 22 decembrie 2021 21:12:33
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

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