Cod sursa(job #2899970)

Utilizator raulandreipopRaul-Andrei Pop raulandreipop Data 9 mai 2022 20:04:51
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <iostream>
#include <vector>
#include <queue>
#define s second
#define f first

using namespace std;

typedef long long ll;

int n, m;
pair<ll , ll> flux[1005][1004];
vector<vector<int>> adj;
bool viz[1001];
int par[1001];

bool bfs ()
{
    
    queue<int> q;
    q.push(1);
    viz[1] = true;
    bool found = 0;
    while (!q.empty())
    {
        int crt = q.front();
        
        q.pop();
        viz[crt] = true;
        if (crt == n){
            return 1;
        }
        else {
            for (auto to : adj[crt])
            {
                if (!viz[to] && flux[crt][to].s - flux[crt][to].f > 0)
                {
                    par[to] = crt;
                    q.push(to);
                }
            }
        }
    }
    return 0;
}

int main ()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    cin >> n >> m;
    adj.resize(n + 1);
    for (int i = 1; i <= m; i++)
    {
        int x, y; ll fx; cin >> x >> y >> fx;
        adj[x].push_back(y);
        adj[y].push_back(x);
        flux[x][y].s += fx;
    //    flux[y][x] = {0, 0};
    }
    ll bottleneck = 0;
    ll ans = 0;
  /*  do {
        bottleneck = bfs();
        ans += bottleneck;
    } while (bottleneck != 0); */

    while (bfs())
    {
        
        for (auto leaf : adj[n])
        {
            if (!viz[leaf] || !(flux[leaf][n].s - flux[leaf][n].f > 0))
                continue;
            par[n] = leaf;
            
            int v = n;
            ll minflow = 1e9;
            while (v != 1)
            {
                minflow = min(minflow, flux[par[v]][v].s - flux[par[v]][v].f);
                if (v == 0) continue;
                v = par[v];
            }
            v = n;
            while (v != 1)
            {
                flux[par[v]][v].f += minflow;
                flux[v][par[v]].f -= minflow;
                v = par[v];
            }
            ans += minflow;
        }
        for (int i = 1; i <= n; i++)
        {
            par[i] = -1;
            viz[i] = 0;
        }
    }

    cout << ans << '\n';
}