Cod sursa(job #2933271)

Utilizator mihnea.cazan15mihnea cazan mihnea.cazan15 Data 4 noiembrie 2022 22:32:34
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>
#define pb push_back
#define ll int

using namespace std;
queue<ll> q;
ll p[1005],f[1005][1005],c[1005][1005],n;
vector<ll> v[1005];
const ll inf=2e9;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

bool ok()
{
    for(int i=2;i<=n;i++)
        p[i]=-1;
    while(!q.empty())
          q.pop();
    q.push(1);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(auto y:v[x])
        {
            if(p[y]==-1 && f[x][y]<c[x][y])
            {
                p[y]=x;
                if(y==n)
                   return true;
                q.push(y);
            }
        }
    }
    return false;
}

ll curr_flow()
{
    ll x=n,ans=inf;
    while(x!=1)
    {
        //cout<<ans<<" ";
        ans=min(ans,c[p[x]][x]-f[p[x]][x]);
        x=p[x];
    }
    return ans;
}

void update(ll flow)
{
    ll x=n;
    while(x!=1)
    {
        f[x][p[x]]-=flow;
        f[p[x]][x]+=flow;
        x=p[x];
    }
    return;
}

ll maxflow()
{
    ll ans=0;
    while(ok())
    {
        ll flow=curr_flow();
        //cout<<flow<<" ";
        //for(int i=1;i<=n;i++)
          //  cout<<p[i]<<" ";
        //cout<<"\n";
        ans+=flow;
        update(flow);
        //step++;
    }
    return ans;
}

int main()
{
    ll m;
    fin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        ll x,y,capacity;
        fin>>x>>y>>capacity;
        v[x].pb(y);
        v[y].pb(x);
        c[x][y]+=capacity;
    }
    fout<<maxflow();
    return 0;
}