Cod sursa(job #1023500)

Utilizator nimeniaPaul Grigoras nimenia Data 7 noiembrie 2013 02:07:37
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <climits>
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>

using namespace std;

#define DBG(x) // std::cout << #x << " " << x << endl

const int MAX_N = 1000 + 2;

int previous[MAX_N], mins[MAX_N];
int c[MAX_N][MAX_N];
vector<int> nodes[MAX_N];

bool bfs(int start, int stop) {
  vector<int>::iterator it;
  queue<int> q;

  memset(previous, 0, sizeof(int) * MAX_N);
  memset(mins, 0, sizeof(int) * MAX_N);

  q.push(start);
  mins[start] = INT_MAX;
  bool found = false;

  while (!q.empty()) {
    int node = q.front(); q.pop();
    //    DBG(node);
    if (node == stop) {
      found = true;
      break;
    }

    DBG(nodes[node].size());
    for (it = nodes[node].begin(); it != nodes[node].end(); it++) {
      //      DBG("here");
      if (c[node][*it] > 0 && previous[*it] == 0) {
        previous[*it] = node;
        mins[*it] = min(mins[node], c[node][*it]);
        q.push(*it);
      }
    }
  }

  return found;
}


void print_c() {
  /*  for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++)
      cout << c[i][j] << " ";
    cout << endl;
    }*/
}


int main(int argc, char *argv[]) {

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

  int n, m, x, y, z;
  scanf("%d %d", &n, &m);

  for (int i = 0; i < m; i++) {
    scanf("%d %d %d", &x, &y, &z);
    c[x][y] = z;
    nodes[x].push_back(y);
  }

  int start = 1, stop = n;
  bool found_path = true;
  int flow = 0;
  while (found_path) {
    found_path = bfs(start, stop);
    if (found_path) {
      DBG("Found path ");
      // update the residual capacity along the path
      int node = stop;
      DBG(mins[stop]);
      while (node != start) {
        DBG(node);
        c[previous[node]][node] -= mins[stop];
        node = previous[node];
      }
      flow += mins[stop];
      print_c();
    }
  }

  printf("%d\n", flow);
  return 0;
}