Cod sursa(job #2322268)

Utilizator Robert_VRVRobert Vadastreanu Robert_VRV Data 17 ianuarie 2019 17:13:12
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <queue>
#include <stdio.h>
#include <vector>

const int MAX_N = 1000;
const int INF = 2e9;

std::vector<int> G[1 + MAX_N];
int r[1 + MAX_N][1 + MAX_N];
int father[1 + MAX_N];
bool visited[1 + MAX_N];

bool bfs(const int& n, int u) {
  std::queue<int> q;
  q.push(u);
  visited[u] = true;
  while (!q.empty() && !visited[n]) {
    int u = q.front();
    q.pop();
    for (int v : G[u])
      if (!visited[v] && r[u][v] > 0) {
        q.push(v);
        visited[v] = true;
        father[v] = u;
      }
  }
  return visited[n];
}

int main() {

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

  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int u, v, capacity;
    scanf("%d%d%d", &u, &v, &capacity);
    r[u][v] = capacity;
    r[v][u] = capacity;
    G[u].push_back(v);
    G[v].push_back(u);
  }

  int maxFlow = 0;
  while (bfs(n, 1)) {
    for (int u : G[n]) {
      father[n] = u;
      int flow = INF;
      int node = n;
      while (node != 1) {
        flow = std::min(flow, r[node][father[node]]);
        node = father[node];
      }
      node = n;
      while (node != 1) {
        r[node][father[node]] -= flow;
        r[father[node]][node] -= flow;
        node = father[node];
      }
      maxFlow += flow;
    }
    for (int i = 1; i <= n; i++)
      visited[i] = false;
  }
  printf("%d\n", maxFlow);

  fclose(stdin);
  fclose(stdout);

  return 0;
}