Cod sursa(job #1555537)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 23 decembrie 2015 00:27:03
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
// typo
#include <fstream>
#include <algorithm>

using namespace std;

const int kMaxN = 1000;
const int kMaxM = 5000;
const int kInf = 2e9;
const int NIL = -1;

struct Edge {
  short v;
  short next;
  int cap;
};

Edge l[2 * kMaxM];
short adj[kMaxN];
short father[kMaxN];
short edgePointer[kMaxN];
short Q[kMaxN];
int qStart, qEnd;
int N;

void addEdge(const short &u, const short &v, const int &cap, const short &pos) {
  l[pos].v = v;
  l[pos].cap = cap;
  l[pos].next = adj[u];
  adj[u] = pos;
}

int BFS(const int &source, const int &sink) {
  for (int i = 0; i < N; i++) {
    father[i] = NIL;
  }
  Q[0] = source;
  qStart = 0;
  qEnd = 1;
  do {
    short u = Q[qStart++];
    for (register short i = adj[u]; i != NIL; i = l[i].next) {
      short v = l[i].v;
      if (father[v] == NIL && l[i].cap) {
        father[v] = u;
        edgePointer[v] = i;
        Q[qEnd++] = v;
      }
    }
  } while ((qStart != qEnd) && (father[sink] == NIL));

  int flow = 0;

  for (register short i = adj[sink]; i != NIL; i = l[i].next) {
    short v = l[i].v;
    if ((father[v] != NIL) && (l[i ^ 1].cap)) {
      father[sink] = v;
      edgePointer[sink] = i ^ 1;

      int minFlow = kInf;

      short u = sink;
      do {
        minFlow = min(minFlow, l[edgePointer[u]].cap);
        u = father[u];
      } while (u != source);

      u = sink;
      do {
        l[edgePointer[u]].cap -= minFlow;
        l[edgePointer[u] ^ 1].cap += minFlow;
        u = father[u];
      } while (u != source);

      flow += minFlow;
    }
  }
  return flow;
}

int main(void) {
  ifstream in("maxflow.in");
  ofstream out("maxflow.out");
  in.tie(0);
  ios_base::sync_with_stdio(0);
  int M;

  in >> N >> M;
  for (register int i = 0; i < N; i++) {
    adj[i] = NIL;
  }
  for (register int i = 0; i < M; i++) {
    short u, v;
    int cap;
    in >> u >> v >> cap;
    addEdge(u - 1, v - 1, cap, 2 * i);
    addEdge(v - 1, u - 1, 0, 2 * i + 1);
  }
  in.close();

  int flow = 0, augment;
  do {
    augment = BFS(0, N - 1);
    flow += augment;
  } while (augment);

  out << flow << '\n';
  out.close();
  return 0;
}