Cod sursa(job #2592589)

Utilizator popashtefan10Popa Stefan popashtefan10 Data 1 aprilie 2020 21:49:37
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#define NMAX 1000
#define MMAX 5000
#define INF 550000000

using namespace std;

bool dest;
int n, m, flux_tot, flux;
int f[NMAX + 5][NMAX + 5], c[NMAX + 5][NMAX + 5];
int from[NMAX + 5], mincf[NMAX + 5];
vector<int> v[NMAX + 5];

void update_flux() {
  int minf = INF + 5;
  for(int i = n; from[i] != 0; i = from[i])
    minf = min(minf, c[from[i]][i] - f[from[i]][i]);
  if(!minf)
    return;
  flux_tot += minf;
  for(int i = n; from[i] != 0; i = from[i]) {
    f[from[i]][i] += minf;
    f[i][from[i]] -= minf;
  }
}

void bfs(int start) {
  queue<int> q;
  q.push(start);

  while(!q.empty()) {
    int nod = q.front();
    q.pop();
    if(nod == n) {
      dest = true;
      continue;
    }

    for(int x: v[nod]) {
      if(from[x] || c[nod][x] == f[nod][x] || x == 1)
        continue;
      from[x] = nod;
      q.push(x);
    }
  }
}

int main() {
  freopen("maxflow.in", "r", stdin);
  freopen("maxflow.out", "w", stdout);
  int x, y, z;

  scanf("%d %d", &n, &m);
  for(int i = 1; i <= m; i++) {
    scanf("%d %d %d", &x, &y, &z);
    c[x][y] = z;
    v[x].push_back(y);
    v[y].push_back(x);
  }

  dest = true;
  mincf[0] = c[0][1] = INF + 5;
  while(dest) {
    for(int i = 1; i <= n; i++)
      from[i] = 0;
    dest = false;
    bfs(1);
    if(!dest)
      break;
    for(int nod: v[n]) {
      if(c[nod][n] == f[nod][n] || (from[nod] == 0 && nod != 1))
        continue;
      from[n] = nod;
      update_flux();
    }
  }

  printf("%d", flux_tot);

  return 0;
}