Cod sursa(job #2955054)

Utilizator smunteanuMunteanu Stefan Catalin smunteanu Data 16 decembrie 2022 00:07:47
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
using namespace std;

const int nmax = 1007;

int n, m;
vector<int> adj[nmax];
int cap[nmax][nmax];
int par[nmax];

void bfs() {

  memset(par, -1, sizeof(par));

  queue<int> q;
  q.push(1);
  par[1] = 0;

  while (!q.empty()) {
    int u = q.front(); q.pop();
    for (int v : adj[u]) {
      if (cap[u][v] > 0 && par[v] == -1) {
        par[v] = u;
        if (v != n) q.push(v);
      }
    }
  }
}

int solve() {

  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v, f;
    cin >> u >> v >> f;
    adj[u].push_back(v);
    adj[v].push_back(u);
    cap[u][v] += f;
  }

  int totalFlow = 0;

  for (;;) {

    bfs();

    if (par[n] == -1) return totalFlow;

    for (int v : adj[n]) {

      if (par[v] == -1 || cap[v][n] == 0) continue;

      int currentFlow = INT_MAX;

      par[n] = v;

      for (int u = n; u != 1; u = par[u]) {
        currentFlow = min(currentFlow, cap[par[u]][u]);
      }

      if (currentFlow == 0) continue;

      for (int u = n; u != 1; u = par[u]) {
        cap[par[u]][u] -= currentFlow;
        cap[u][par[u]] += currentFlow;
      }

      totalFlow += currentFlow;
    }

  }
}

int main() {
  
  #ifdef LOCAL
  freopen("file.in", "r", stdin);
  #else
  freopen("maxflow.in", "r", stdin);
  freopen("maxflow.out", "w", stdout);
  #endif

  ios_base::sync_with_stdio(false), cin.tie(NULL);

  cout << solve() << endl;
}