Cod sursa(job #2085457)

Utilizator MiricaMateiMirica Matei MiricaMatei Data 10 decembrie 2017 11:20:30
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1000;

vector<int>G[MAX_N + 5];
bool viz[MAX_N + 5];
int from[MAX_N + 5];
int cr[MAX_N + 5][MAX_N + 5];

bool bfs(int s, int d) {
  viz[s] = 1;
  queue<int>q;
  q.push(s);
  while (!q.empty()) {
    int node = q.front();
    q.pop();
    for (auto it:G[node]) {
      if (!viz[it] && cr[node][it] > 0) {
        from[it] = node;
        viz[it] = 1;
        q.push(it);
      }
    }
  }
  return viz[d];
}

int maxFlow(int s, int d) {
  int ans = 0;
  while (bfs(s, d)) {
    for (auto it:G[d]) {
      int aux = (1LL << 31) - 1;
      if (cr[it][d] == 0 || !viz[it])
        continue;
      int node = d;
      from[d] = it;
      while (node != s) {
        aux = min(aux, cr[from[node]][node]);
        node = from[node];
      }
      node = d;
      while (node != s) {
        cr[from[node]][node] -= aux;
        cr[node][from[node]] += aux;
        node = from[node];
      }
      ans += aux;
    }
    memset(viz, 0, sizeof(viz));
  }
  return ans;
}

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, c;
    scanf("%d%d%d", &u, &v, &c);
    if (cr[u][v] == 0) {
      G[u].push_back(v);
      G[v].push_back(u);
    }
    cr[u][v] = c;
  }

  printf("%d\n", maxFlow(1, n));

  return 0;
}