Cod sursa(job #3293249)

Utilizator mircea_007Mircea Rebengiuc mircea_007 Data 10 aprilie 2025 23:44:57
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <stdio.h>
#include <queue>
#include <vector>
#include <algorithm>

namespace Flow {
  constexpr int INF = 1e9;
  const int MAXN = 1000;

  int n;
  std::vector<int> adj[MAXN];
  int cap[MAXN][MAXN];
  int dist[MAXN];

  void init( int __n ) { n = __n; }

  void push_edge( int a, int b, int __cap ) {
    adj[a].push_back( b );
    adj[b].push_back( a );
    cap[a][b] = __cap; // muchia a-->b este orientata
  }

  bool bfs( int src, int dest ) {
    for( int i = 0; i < n; i++ )
      dist[i] = +INF;

    std::queue<int> q({ src });
    dist[src] = 0;

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

      for( int v : adj[u] )
        if( cap[u][v] && dist[u] + 1 < dist[v] ){
          dist[v] = 1 + dist[u];
          q.push( v );
        }
    }

    return dist[dest] < +INF;
  }

  int search_idx[MAXN];
  int dinic( int src, int dest, int push ) {
    if( !push ) return 0;
    if( src == dest ) return push;

    for( int &idx = search_idx[src]; idx < (int)adj[src].size(); idx++ ){
      int u = adj[src][idx];
      if( !cap[src][u] ) continue;
      if( dist[u] != dist[src] + 1 ) continue;

      int try_push = dinic( u, dest, std::min( push, cap[src][u] ) );
      if( !try_push ) continue;

      cap[src][u] -= try_push;
      cap[u][src] += try_push;
      return try_push;
    }

    return 0;
  }

  int push_flow( int src, int dest ) {
    int flow = 0;

    while( bfs( src, dest ) ){
      for( int i = 0; i < n; i++ )
        search_idx[i] = 0;

      int push;
      while( (push = dinic( src, dest, +INF )) )
        flow += push;
    }

    return flow;
  }
}

int main() {
  FILE *fin = fopen( "maxflow.in", "r" );
  FILE *fout = fopen( "maxflow.out", "w" );

  int n, m;
  fscanf( fin, "%d%d", &n, &m );
  int src = 0, dest = n - 1;

  Flow::init( n );
  for( int i = 0; i < m; i++ ){
    int a, b, cap;
    fscanf( fin, "%d%d%d", &a, &b, &cap );
    Flow::push_edge( --a, --b, cap );
  }

  fprintf( fout, "%d\n", Flow::push_flow( src, dest ) );

  fclose( fin );
  fclose( fout );
}