Cod sursa(job #2984956)

Utilizator MoodyFaresFares Mohamad MoodyFares Data 25 februarie 2023 12:08:42
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1000;

int n;
int c[1 + MAX_N][1 + MAX_N];
int f[1 + MAX_N][1 + MAX_N];
vector<int> g[1 + MAX_N];
bool vis[1 + MAX_N];
int from[1 + MAX_N];

void init() {
  for (int i = 1; i <= n; i++) {
    vis[i] = false;
    from[i] = 0;
  }
}

bool bfs() {
  init();

  int s;
  queue<int> q;

  s = 1;
  q.push(s);
  vis[s] = true;
  from[s] = 0;
  while (!q.empty()) {
    int current = q.front();
    q.pop();

    for (auto u : g[current]) {
      if (u != n && !vis[u] && f[current][u] < c[current][u]) {
        q.push(u);
        vis[u] = true;
        from[u] = current;
      }
    }
  }

  for (auto u : g[n]) {
    if (vis[u] && f[u][n] < c[u][n])
      return true;
  }
  return false;
}

int main() {
  freopen("maxflow.in", "r", stdin);
  freopen("maxflow.out", "w", stdout);

  int m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int u, v, cap;
    scanf("%d%d%d", &u, &v, &cap);
    c[u][v] = cap;

    g[u].push_back(v);
    g[v].push_back(u);
  }

  while (bfs()) {
    for (auto u : g[n]) {
      if (vis[u] && f[u][n] < c[u][n]) {
        int current, minRes;
        minRes = c[u][n] - f[u][n];
        current = u;
        while (current != 1) {
          int prevOnPath = from[current];
          minRes = min(minRes, c[prevOnPath][current] - f[prevOnPath][current]);
          current = prevOnPath;
        }

        f[u][n] += minRes;
        current = u;
        while (current != 1) {
          int prevOnPath = from[current];
          f[prevOnPath][current] += minRes;
          current = prevOnPath;
        }
      }
    }
  }

  int maxFlow = 0;
  for (auto u : g[n])
    maxFlow += f[u][n];
  printf("%d\n", maxFlow);

  return 0;
}