Cod sursa(job #3216203)

Utilizator dorufDoru Floare doruf Data 15 martie 2024 18:26:59
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
#define eb emplace_back
using ll = long long;
using ld = long double;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int N = 5 + 1000, Inf(1e9);
int f[N][N], c[N][N], t[N];
int n, m;
vi g[N];
bitset<N> vis;

void add_edge(int u, int v, int w) {
  g[u].eb(v);
  g[v].eb(u);
  c[u][v] += w;

}

bool bfs(int src, int dest) {
  vis.reset();
  queue<int> q;
  vis[src]=1;
  q.emplace(src);
  while (!q.empty()) {
    int u = q.front();q.pop();
    if (u == dest) continue;
    for (auto v : g[u])
      if (!vis[v] && c[u][v] - f[u][v] > 0) {
        vis[v]=1;
        t[v] = u;
        q.emplace(v);
      }
  }
  return (vis[dest]);
}

int maxflow(int src, int dest) {
  int ret = 0;
  while (bfs(src, dest)) {
    int flow = Inf;
    for (int i = dest; i != src; i = t[i])
      flow = min(flow, c[t[i]][i] - f[t[i]][i]);
     for (int i = dest; i != src; i = t[i]) {
      f[t[i]][i] += flow;
      f[i][t[i]] -= flow;
     }
     ret += flow;
  }
  return ret;
}

int main() {
  ios_base::sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);

  fin >> n >> m;
  for (int u, v, w; m; --m) {
    fin >> u >> v >> w;
    add_edge(u, v, w);
  }
  fout << maxflow(1,n) << '\n';
}