Cod sursa(job #2218280)

Utilizator cella.florescuCella Florescu cella.florescu Data 4 iulie 2018 05:30:17
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e3;

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

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

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