Cod sursa(job #2826667)

Utilizator andreic06Andrei Calota andreic06 Data 5 ianuarie 2022 12:22:33
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;
const int NMAX = 1e3;
const int MMAX = 5e3;
const int INF = 2e9;

struct define_edge {
      int flow, capacity;
} edge[1 + NMAX][1 + NMAX];
vector<int> graph[1 + NMAX];
bool visited[1 + NMAX];
int back_of[1 + NMAX];
int source, sink;
int n, m;

static inline int remaining_capacity ( int u, int v ) {
      return edge[u][v].capacity - edge[u][v].flow;
}

void augment_edge ( int u, int v, int bottleneck ) {
    edge[u][v].flow += bottleneck;
    edge[v][u].flow -= bottleneck;
}

void reset_vis () {
    for ( int i = 1; i <= n; i ++ )
       visited[i] = false;
}

bool bfs ( int b, int e ) {
    queue<int> q; q.push ( b );
    while ( !q.empty () ) {
       int node = q.front ();
       q.pop ();

       visited[node] = true;
       for ( auto next : graph[node] ) {
          if ( !visited[next] && remaining_capacity ( node, next ) ) {
            q.push ( next );
            back_of[next] = node;
            if ( next == e )
              return true;
          }
       }
    }
    return false;
}

int solve_flow () {
   int answer = 0;
   while ( bfs ( source, sink ) ) {
      int node = sink, bottleneck = INF;
      while ( node != source ) {
         bottleneck = min ( bottleneck, remaining_capacity ( back_of[node], node ) );
         node = back_of[node];
      }

      node = sink;
      while ( node != source ) {
         augment_edge ( back_of[node], node, bottleneck );
         node = back_of[node];
      }
      answer += bottleneck;
      reset_vis ();
   }
   return answer;
}


ifstream fin ( "maxflow.in" );
ofstream fout ( "maxflow.out" );
int main()
{
   fin >> n >> m; source = 1, sink = n;
   for ( int i = 1; i <= m; i ++ ) {
      int u, v, cap; fin >> u >> v >> cap;
      edge[u][v] = { 0, cap };
      graph[u].push_back ( v );
      graph[v].push_back ( u );
   }

   for ( int node = 1; node <= n; node ++ )
      random_shuffle ( graph[node].begin (), graph[node].end () );

   fout << solve_flow ();
    return 0;
}