Cod sursa(job #3293760)

Utilizator pacelaaaCiurea Pavel pacelaaa Data 12 aprilie 2025 15:31:34
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>

using namespace std;

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

#define cin fin
#define cout fout
#define PB push_back
#define S second
#define F first
#define FR( a, b) for( int a = 0; a < (int) b; a ++ )
#define FOR( a, c, b) for( int a = c; a < (int) b; a ++ )

const int Nmax = 1001;
int tt[Nmax], c[Nmax][Nmax], f[Nmax][Nmax];
vector<int> adj[Nmax];
bool parcurs[Nmax];
queue<int> q;

int n;
bool bfs() {
  int u, nod;
  FOR( i, 1, n + 1 )
    parcurs[i] = false;

  q.push( 1 );
  parcurs[1] = true;
  while( !q.empty() ) {
    u = q.front();
    q.pop();

    if( u  == n )
      continue;
    FR( i, adj[u].size() ) {
      nod = adj[u][i];
      if( !parcurs[nod] && c[u][nod] != f[u][nod] ) {
        q.push( nod );
        tt[nod] = u;
        parcurs[nod] = true;
      }
    }
  }

  return parcurs[n];
}

int main()
{
    int m, u, nod, flow, flux, flow_crt;

    cin >> n >> m;
    FR( i, m ) {
      cin >> u >> nod >> flow;
      adj[u].PB( nod );
      adj[nod].PB( u );
      c[u][nod] = flow;
    }

    flux = 0;
    while( bfs() ) {
      FR( i, adj[n].size() ) {
        u = adj[n][i];
        if( !parcurs[u] )
          continue;

        flow_crt = c[u][n] -f[u][n];
        while( tt[u] != 0 ) {
          flow_crt = min( flow_crt, c[tt[u]][u] - f[tt[u]][u] );
          u = tt[u];
        }
        u = adj[n][i];
        f[u][n] += flow_crt;
        f[n][u] -= flow_crt;
        while( u != 1 ) {
          f[tt[u]][u] += flow_crt;
          f[u][tt[u]] -= flow_crt;
          u = tt[u];
        }

        flux += flow_crt;
      }
    }

    cout << flux << '\n';
    return 0;
}