Cod sursa(job #3144238)

Utilizator Raul_AArdelean Raul Raul_A Data 6 august 2023 16:08:20
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
#define cin in
#define cout out
#define ll long long
#define eb emplace_back
#define pii pair<int, int>
#define tpl tuple<int, int, int>
using namespace std;

const string file_name("maxflow");

ifstream in(file_name + ".in");
ofstream out(file_name + ".out");

int n,k,x,y,c,lvl[1005],p[1005];
ll cost[1005][1005];
vector<pii> g[1005];


bool bfs(int s,int t)
{
    memset(lvl,0,sizeof(lvl));
    memset(p,0,sizeof(p));
    queue<int> q;

    lvl[s]=1;
    q.push(s);

    while(!q.empty())
    {
        int k=q.front();
        q.pop();

        for(auto x: g[k])
            if(cost[k][x.first]<x.second and lvl[x.first]==0)
            {
                lvl[x.first]=lvl[k]+1;
                q.push(x.first);
            }
    }

    return lvl[t]!=0;
}

int sendflow(int k,ll flow)
{
    if(k==n or flow==0) return flow;
    while(p[k]<g[k].size())
    {
        pii x=g[k][p[k]];
        p[k]++;
        if(lvl[x.first]==lvl[k]+1 and cost[k][x.first]<x.second)
        {
            ll minflow=min(flow,x.second-cost[k][x.first]);
            ll revflow=sendflow(x.first,minflow);

            if(revflow!=0)
            {
                cost[k][x.first]+=revflow;
                return revflow;
            }
        }
    }
    return 0;
}

int main()
{
    cin>>n>>k;

    while(k--)
    {
        cin>>x>>y>>c;
        g[x].eb(y,c);
    }
    ll ans=0;
    while(bfs(1,n))
    {
        while(ll flow=sendflow(1,LLONG_MAX))
        {
            ans+=flow;
        }
    }
    cout<<ans;
    return 0;
}