Cod sursa(job #2247130)

Utilizator MiricaMateiMirica Matei MiricaMatei Data 27 septembrie 2018 21:59:20
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1005;
const int MAXM = 10005;

struct maxFlow {

  vector<int>G[MAXN];
  int from[MAXN];
  int last;

  maxFlow () {
    last = 0;
  }

  struct Edge {
    int x, y, cap, flow, inv;
    int other(int nod) {
      return x ^ y ^ nod;
    }
    int ramas() {
      return cap - flow;
    }
  } E[MAXM];

  void addEdge(int x, int y, int c) {
    E[++last] = {x, y, c, 0, last + 1};
    G[x].push_back(last);
    E[++last] = {y, x, 0, 0, last - 1};
    G[y].push_back(last);
  }

  bool bfs(int s, int d) {
    queue<int>q;
    q.push(s);
    memset(from, -1, sizeof(from));
    from[s] = 0;
    while (!q.empty() && from[d] == -1) {
      int aux = q.front();
      q.pop();
      for (auto it:G[aux]) {
        int x = E[it].other(aux);
        if (from[x] == -1 && E[it].ramas() > 0) {
          from[x] = it;
          q.push(x);
        }
      }
    }
    return (from[d] != -1);
  }

  int baga(int s, int d) {
    int ans = 0;
    while (bfs(s, d)) {
      for (auto it:G[d]) {
        int minim = (1LL << 31) - 1;
        if (minim == 0 || from[E[it].other(d)] == -1)
          continue;
        int nod = d;
        int muc = E[it].inv;
        while (nod != s) {
          minim = min(minim, E[muc].ramas());
          nod = E[muc].other(nod);
          muc = from[nod];
        }
        nod = d;
        muc = E[it].inv;
        while (nod != s) {
          E[muc].flow += minim;
          E[E[muc].inv].flow -= minim;
          nod = E[muc].other(nod);
          muc = from[nod];
        }
        ans += minim;
      }
    }
    return ans;
  }
};

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

  int n, m;
  scanf("%d%d", &n, &m);
  maxFlow s;
  for (int i = 1; i <= m; ++i) {
    int x, y, c;
    scanf("%d%d%d", &x, &y, &c);
    s.addEdge(x, y, c);
  }

  printf("%d\n", s.baga(1, n));

  return 0;
}