Cod sursa(job #2286172)

Utilizator ApostolIlieDanielApostol Daniel ApostolIlieDaniel Data 19 noiembrie 2018 21:32:52
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>

using namespace std;

FILE *fin = fopen ("maxflow.in", "r"), *fout = fopen ("maxflow.out", "w");

const int MAXN = 1000, INF = 1e9;

int dist[MAXN + 1], q[MAXN + 1], nxt[MAXN + 1], c[MAXN + 1][MAXN + 1];
vector <int> gr[MAXN + 1];

int n;

int bfs () {
  int e, b, nod;
  memset (dist, 0, sizeof (dist));
  e = 0;
  b = 0;
  q[e] = 1;
  nxt[1] = 0;
  dist[1] = 1;
  while (e <= b) {
    nod = q[e++];
    for (auto fiu : gr[nod]) {
      if (c[nod][fiu] > 0 && dist[fiu] == 0) {
        q[++b] = fiu;
        dist[fiu] = dist[nod] + 1;
        nxt[fiu] = nod;
      }
    }
  }
  return dist[n];
}

int update () {
  int nod, nr, flow;
  nod = n;
  nr = 0;
  flow = INF;
  while (nod != 1) {
    nr++;
    flow = min (flow, c[nxt[nod]][nod]);
    if (nr > n * 2)
      return 0;
    nod = nxt[nod];
  }
  nod = n;
  while (nod != 1) {
    c[nxt[nod]][nod] -= flow;
    c[nod][nxt[nod]] += flow;
    nod = nxt[nod];
  }
  return flow;
}

int main() {
  int m, x, y, cap, sol, i;
  fscanf (fin, "%d%d", &n, &m);
  for (i = 1; i <= m; i++) {
    fscanf (fin, "%d%d%d", &x, &y, &cap);
    c[x][y] = c[x][y] + cap;
    gr[x].push_back (y);
    gr[y].push_back (x);
  }
  sol = 0;
  while (bfs ()) {
    for (auto fiu : gr[n]) {
      nxt[n] = fiu;
      sol = sol + update ();
    }
  }
  fprintf (fout, "%d\n", sol);
  fclose (fin);
  fclose (fout);
  return 0;
}