Cod sursa(job #2908756)

Utilizator vladburacBurac Vlad vladburac Data 5 iunie 2022 18:03:55
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1000;

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

vector <int> edges[NMAX+1];
int capacity[NMAX+1][NMAX+1];

int source, dest;
int parent[NMAX+1];
int n, new_flow;

void dfs( int node, int flow ) {
  if( node == dest )
    new_flow = flow;
  for( auto it: edges[node] ) {
    if( !parent[it] && capacity[node][it] ) {
      parent[it] = node;
      dfs( it, min( flow, capacity[node][it] ) );
    }
  }
}
int main() {
  int m, a, b, c, in, out, node, flow, i;
  fin >> n >> m;
  for( i = 0; i < m; i++ ) {
    fin >> a >> b >> c;
    capacity[a][b] = c;
    edges[a].push_back( b );
    edges[b].push_back( a );
  }
  for( i = 1; i <= n; i++ ) {
    in = out = 0;
    for( auto it: edges[i] ) {
      if( capacity[i][it] > 0 )
        out++;
      else if( capacity[it][i] > 0 )
        in++;
    }
    if( in == 0 )
      source = i;
    if( out == 0 )
      dest = i;
  }
  parent[source] = -1;
  dfs( source, 1e9 );
  flow = 0;
  while( parent[dest] ) {
    node = dest;
    while( node != source ) {
      capacity[parent[node]][node] -= new_flow;
      capacity[node][parent[node]] += new_flow;
      node = parent[node];
    }
    flow += new_flow;
    for( i = 1; i <= n; i++ )
      parent[i] = 0;
    parent[source] = -1;
    dfs( source, 1e9 );
  }
  fout << flow;
  return 0;
}