Cod sursa(job #2971840)

Utilizator andu2006Alexandru Gheorghies andu2006 Data 28 ianuarie 2023 10:31:53
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <bits/stdc++.h>
//#pragma GCC optimize("unroll-loops")

using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
/*int Time(){
    return chrono::steady_clock::now().time_since_epoch().count();
}
random_device rd;
mt19937_64 gen(rd());
int uniform_rand(int l, int r){
    uniform_int_distribution<ll> rnd(l,r);
    return rnd(gen);
}*/
const int NMAX=1e3+5;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector<ll> edg[NMAX];
bool adj[NMAX][NMAX];
ll cap[NMAX][NMAX];
ll s,t,ans,dist[NMAX],ptr[NMAX];
ll flux(ll u,ll f){
    if(f==0 || u==t) return f;
    for(ll& i=ptr[u];i<edg[u].size();i++){
        ll v=edg[u][i];
        if(dist[v]==dist[u]+1 && cap[u][v]){
            ll augment=flux(v,min(f,cap[u][v]));
            if(augment>0){
                cap[u][v]-=augment;
                cap[v][u]+=augment;
                return augment;
            }
        }
    }
    return 0;
}
int main()
{
    ios_base::sync_with_stdio(false); fin.tie(0);
    ll n,m;
    fin>>n>>m;
    for(ll i=0;i<m;i++){
        ll u,v,c;
        fin>>u>>v>>c;
        cap[u][v]+=c;
        adj[u][v]=adj[v][u]=1;
    }
    for(ll i=1;i<=n;i++) for(ll j=1;j<=m;j++){
        if(adj[i][j])
            edg[i].push_back(j);
    }
    s=1,t=n;
    while(1){
        for(ll i=0;i<=n;i++) dist[i]=-1,ptr[i]=0;
        queue<ll> q;
        q.push(s),dist[s]=0;
        while(!q.empty()){
            for(auto it : edg[q.front()]){
                if(dist[it]==-1 && cap[q.front()][it]>0){
                    dist[it]=dist[q.front()]+1;
                    q.push(it);
                    if(it==t) break;
                }
            }
            q.pop();
        }
        if(dist[t]==-1) break;
        ll f=1,iter=0;
        while((f=flux(s,INT_MAX))>0)
            ans+=f,iter++;
        if(iter==0) break;
    }
    fout<<ans<<'\n';

    return 0;
}