Cod sursa(job #1790255)

Utilizator cella.florescuCella Florescu cella.florescu Data 27 octombrie 2016 22:24:27
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1000;
const int INF = 531800008;

int seen[MAXN + 1], cap[MAXN + 1][MAXN + 1], flow[MAXN + 1][MAXN + 1], father[MAXN + 1];
queue <int> q;
vector <int> g[MAXN + 1];

int bfs(int n) {
  memset(seen, 0, sizeof(seen));
  seen[1] = 1;
  q.push(1);
  int node;
  while (q.empty() == 0) {
    node = q.front();
    if (node != n)
      for (auto it : g[node])
        if (cap[node][it] > flow[node][it] && seen[it] == 0) {
          father[it] = node;
          q.push(it);
          seen[it] = 1;
        }
    q.pop();
  }
  return seen[n];
}

inline int minim(int a, int b) {
  if (a < b)
    return a;
  return b;
}

int main()
{
    int n, m, x, y, z, i, maxfl, fl;
    ifstream fin("maxflow.in");
    fin >> n >> m;
    for (i = 0; i < m; ++i) {
      fin >> x >> y >> z;
      g[x].push_back(y);
      g[y].push_back(x);
      cap[x][y] += z;
    }
    fin.close();
    maxfl = 0;
    while (bfs(n)) {
      for (auto it : g[n])
        if (seen[it] && flow[it][n] < cap[it][n]) {
          father[n] = it; fl = INF; i = n;
          while (i > 1) {
            fl = minim(fl, cap[father[i]][i] - flow[father[i]][i]);
            i = father[i];
          }
          i = n;
          while (i > 1) {
            flow[father[i]][i] += fl;
            flow[i][father[i]] -= fl;
            i = father[i];
          }
          maxfl += fl;
        }
    }
    ofstream fout("maxflow.out");
    fout << maxfl << '\n';
    fout.close();
    return 0;
}