Cod sursa(job #1162124)

Utilizator thebest001Neagu Rares Florian thebest001 Data 31 martie 2014 17:24:10
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;

#define INF 0x3f3f3f3f
#define MAX 1200

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

vector<int> g[MAX];
int F[MAX][MAX];
int C[MAX][MAX];
int pred[MAX];
int n;
queue<int> coada;

bool BFS() {
  coada.push(1);
  while (!coada.empty()) {
    int nod = coada.front();coada.pop();

    for (int i = 0; i < g[nod].size(); i++) {
      if (F[nod][ g[nod][i] ] < C[nod][g[nod][i]] && !pred[g[nod][i]]){
        pred[g[nod][i]] = nod;
        coada.push(g[nod][i]);
      }
    }
  }
  if (pred[n] == 0)
    return false;
  return true;
}

int minim(int x){
  int m = INF;
  while (x != 1) {
    if (C[pred[x]][x] - F[pred[x]][x] < m) {
      m = C[pred[x]][x] - F[pred[x]][x];
    }
    x = pred[x];
  }
  return m;
}

void drum(int x, int vf) {
  while (x != 1) {
    F[pred[x]][x] += vf;
    F[x][pred[x]] -= vf;
    x = pred[x];
  }
}

int main() {
  int m = 0;
  in>>n>>m;
  for (int i = 1; i <= m; i++) {
    int x, y, c;
    in>>x>>y>>c;
    C[x][y] = c;
    g[x].push_back(y);
    g[y].push_back(x);
  }

  while (BFS()) {
    int m = minim(n);
    drum(n, m);
    memset(pred, 0, sizeof(pred));
  }

  m = 0;
  for (int i = 0; i < g[1].size(); i++) {
    m+=F[1][g[1][i]];
  }
  out<<m<<"\n";

  return 0;
}