Cod sursa(job #2078177)

Utilizator DruffbaumPopescu Vlad Druffbaum Data 28 noiembrie 2017 23:50:23
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>

const int INF = 2e9;
const int MAXN = 1e3;

std::vector <int> g[MAXN + 1];
int flow[MAXN + 1][MAXN + 1], cap[MAXN + 1][MAXN + 1],
    fath[MAXN + 1];
bool vis[MAXN + 1];
std::queue <int> q;

static inline int min(int a, int b) {
  return a > b ? b : a;
}

bool bfs(int n) {
  int u;
  memset(vis, 0, sizeof(vis));
  vis[1] = 1;
  q.push(1);
  while (!q.empty()) {
    u = q.front();
    if (u != n) {
      for (auto v: g[u]) {
        if (!vis[v] && flow[u][v] < cap[u][v]) {
          vis[v] = 1;
          fath[v] = u;
          q.push(v);
        }
      }
    }
    q.pop();
  }
  return vis[n];
}

int main() {
  int n, m, u, v, c, fl, maxfl;
  FILE *f = fopen("maxflow.in", "r");
  fscanf(f, "%d%d", &n, &m);
  for (int i = 0; i < m; ++i) {
    fscanf(f, "%d%d%d", &u, &v, &c);
    g[u].push_back(v);
    g[v].push_back(u);
    cap[u][v] += c;
  }
  fclose(f);
  maxfl = 0;
  while (bfs(n)) {
    for (auto u: g[n]) {
      if (vis[u] && flow[u][n] < cap[u][n]) {
        fath[n] = u;
        fl = INF;
        v = n;
        while (v > 1) {
          fl = min(fl, cap[fath[v]][v] - flow[fath[v]][v]); 
          v = fath[v];
        }
        v = n;
        while (v > 1) {
          flow[fath[v]][v] += fl;
          flow[v][fath[v]] -= fl;
          v = fath[v];
        }
        maxfl += fl;
      }
    }
  }
  f = fopen("maxflow.out", "w");
  fprintf(f, "%d\n", maxfl);
  fclose(f);
  return 0;
}