Cod sursa(job #2953708)

Utilizator smunteanuMunteanu Stefan Catalin smunteanu Data 12 decembrie 2022 00:04:23
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
using namespace std;

struct Edge {
  int u = 0, v = 0, c = 0, f = 0;
};

const int nmax = 1007;
typedef long long llong;

static int n, m;
static vector<Edge> adj[nmax];
static Edge* pred[nmax];

void bfs() {
  
  queue<int> q;
  q.push(1);

  while (!q.empty()) {
    int u = q.front(); q.pop();
    for (Edge& e : adj[u]) {
      if (pred[e.v] == NULL && e.c > e.f) {
        pred[e.v] = &e;
        q.push(e.v);
      }
    }
  }

}

void solve() {

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

  llong totalFlow = 0;

  for (;;) {

    memset(pred, 0, sizeof pred);
    
    bfs();

    if (pred[n]) {
      
      int currentFlow = INT_MAX;

      for (int it = n; pred[it]; it = pred[it]->u) {
        currentFlow = min(currentFlow, pred[it]->c - pred[it]->f);
      }

      for (int it = n; pred[it]; it = pred[it]->u) {
        pred[it]->f += currentFlow;
      }

      totalFlow += currentFlow;

    } else break;

  }

  cout << totalFlow << endl;

}

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);

  solve();
}