Cod sursa(job #3262227)

Utilizator nstefanNeagu Stefan nstefan Data 9 decembrie 2024 13:01:21
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>
using namespace std;
#define int long long
int N,M;
vector<int> ad[501];
int flux_trimis[501][501],capacitate[501][501],from[501];
bool b[501];
queue<int>been;
inline bool bfs(int node) {
    queue<int>q;
    q.push(node);
    been.push(node);
    b[node] = true;
    while (q.size()) {
        auto i = q.front();
        q.pop();
        for (int j : ad[i])
            if (capacitate[i][j] - flux_trimis[i][j] > 0 && !b[j]){
                q.push(j);
                been.push(j);
                from[j] = i;
                b[j] = true;
                }
    }
    return b[N];
}
 
inline int getMin(int node) {
    int mn = (int)1e18;
    while (from[node]) {
        mn = min(mn,capacitate[from[node]][node] - flux_trimis[from[node]][node]);
        node = from[node];
    }
    return mn;
}
 
inline void update(int node,int mn) {
    while (from[node]) {
        flux_trimis[from[node]][node] += mn;
        flux_trimis[node][from[node]] -= mn;
        node = from[node];
    }
}
 
main(){
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","o",stdout);
    
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> N >> M;
    while (M--) {
        int u,v,c;
        cin >> u >> v >> c;
        capacitate[u][v] += c;
        ad[u].push_back(v);
        ad[v].push_back(u);
    }
    int ans = 0;
    while (bfs(1)) {
        for (int i : ad[N]) {
            if (b[i]) {
                from[N] = i;
                int mn = getMin(N);
                update(N,mn);
                ans += mn;
            }
        }
        while (been.size()) {
            auto i = been.front();
            b[i] = false;
            been.pop();
        }
    }
    cout << ans;
}