Cod sursa(job #1806927)

Utilizator BrandonChris Luntraru Brandon Data 15 noiembrie 2016 20:39:54
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>

#define Pe pair <int, int>
#define mp make_pair
#define fi first
#define se second
using namespace std;

const int MaxN = 1005, Inf = 0x3f3f3f3f;

int n, m, Ans;
int G[MaxN][MaxN], father[MaxN], Flow[MaxN][MaxN];
queue <int> Q;

inline void QClear() {
  while (Q.size()) {
    Q.pop();
  }
}

int Bfs() {
  QClear();
  memset(father, 0, sizeof father);
  father[1] = -1;
  Q.push(1);
  while (Q.size()) {
    int node = Q.front();
    Q.pop();
    if (node == n) {
      continue;
    }

    for (int i = 1; i <= n; ++i) {
      if (!father[i] and G[node][i] - Flow[node][i]) {
        Q.push(i);
        father[i] = node;
      }
    }
  }

  return father[n];
}

int RoadCap(int node = n) {
  int ans = Inf;
  while (father[node] != -1) {
    int parent = father[node];
    ans = min(ans, G[parent][node] - Flow[parent][node]);
    node = parent;
  }

  return ans;
}

void Pump(int Quantity, int node = n) {
  while (father[node] != -1) {
    int parent = father[node];
    Flow[parent][node] += Quantity;
    Flow[node][parent] -= Quantity;
    node = parent;
  }
}

int main() {
  freopen("maxflow.in", "r", stdin);
  freopen("maxflow.out", "w", stdout);
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; ++i) {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    G[a][b] = c;
  }

  while (Bfs()) {
    for (int i = 1; i < n; ++i) {
      if (!G[i][n]) {
        continue;
      }

      if (!(G[i][n] - Flow[i][n]) or !father[i]) {
        continue;
      }

      father[n] = i;
      int CurrCap = RoadCap();
      if (CurrCap == 0) {
        continue;
      }
      Pump(CurrCap);
    }
  }

  for (int i = 2; i <= n; ++i) {
    if (!G[1][i]) {
      continue;
    }

    Ans += Flow[1][i];
  }

  printf("%d\n", Ans);
  return 0;
}