Cod sursa(job #2247125)

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

using namespace std;

const int MAXN = 1005;
const int MAXM = 5005;

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

int last;

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 maxFlow(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);
  for (int i = 1; i <= m; ++i) {
    int x, y, c;
    scanf("%d%d%d", &x, &y, &c);
    addEdge(x, y, c);
  }

  printf("%d\n", maxFlow(1, n));

  return 0;
}