Cod sursa(job #1545871)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 7 decembrie 2015 11:54:39
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <queue>
#include <cstdio>
#include <vector>

using namespace std;

const int MAX_N = 1000, MAX_INF = 0x3fffffff;

int n, m, totalFlow;

vector < int > G[1 + MAX_N];
int capacitate[1 + MAX_N][1 + MAX_N];

vector < int > GL[1 + MAX_N];
queue < int > coada;
bool vizitat[1 + MAX_N];
int adancime[1 + MAX_N], tata[1 + MAX_N];

bool buildGL()
{
  for (int i = 1; i <= n; i++)
    vizitat[i] = false;

  int nod = 1;
  vizitat[nod] = true;
  coada.push(nod);
  adancime[nod] = 0;
  while (!coada.empty())
  {
    nod = coada.front();
    coada.pop();
    //for (int i = 0; i < G[nod].size(); i++)
    //{
    //  int vecin = G[nod][i];
    for (int vecin : G[nod])
    {
      if (capacitate[nod][vecin] > 0 && !vizitat[vecin])
      {
        coada.push(vecin);
        vizitat[vecin] = true;
        adancime[vecin] = adancime[nod] + 1;
      }
    }
  }

  for (int i = 1; i <= n; i++)
    GL[i].clear();
  for (int nod = 1; nod <= n; nod++) {
    for (int vecin : G[nod]) {
      if (adancime[nod] - adancime[vecin] == -1 && capacitate[nod][vecin] > 0)
        GL[nod].push_back(vecin);
    }
  }

  return vizitat[n];
}

bool BFS() {

  for(int i = 1; i <= n; ++i)
    vizitat[i] = false;
  int nod = 1;
  coada.push(nod);
  vizitat[nod] = true;
  while (!coada.empty()) {
    nod = coada.front(); coada.pop();
    for(int vecin : GL[nod]) {
      if (capacitate[nod][vecin] > 0) {
         tata[vecin] = nod;
         coada.push(vecin);
         vizitat[vecin] = true;
      }
    }
  }
  return vizitat[n];
}

void pushFlow() {
  while(BFS()) {
    int flow = MAX_INF;
    int nod = n;
    while (nod != 1) {
      flow = min(capacitate[tata[nod]][nod], flow);
      nod = tata[nod];
    }

    nod = n;
    while(nod != 1) {
      capacitate[tata[nod]][nod] -= flow;
      capacitate[nod][tata[nod]] += flow;
      nod = tata[nod];
    }
    totalFlow += flow;
  }
}

int main() {
  freopen("maxflow.in", "r", stdin);
  freopen("maxflow.out", "w", stdout);
  scanf("%d%d", &n, &m);
  for(int i = 1; i <= m; ++i) {
    int u, v, c;
    scanf("%d%d%d", &u, &v, &c);
    capacitate[u][v] = c;
    G[u].push_back(v);
    G[v].push_back(u);
  }
  while(buildGL()) {
    pushFlow();
  }
  printf("%d\n", totalFlow);
  return 0;
}