Cod sursa(job #1023501)

Utilizator nimeniaPaul Grigoras nimenia Data 7 noiembrie 2013 02:41:31
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 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];
int flow[MAX_N][MAX_N];
vector<int> nodes[MAX_N];

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

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;
  previous[start] = -1;

  while (!q.empty()) {
    int node = q.front(); q.pop();
    //    DBG(node);
    //    DBG(nodes[node].size());
    for (it = nodes[node].begin(); it != nodes[node].end(); it++) {
      if (c[node][*it] <= flow[node][*it] || previous[*it] != 0)
        continue;
      previous[*it] = node;
      mins[*it] = min(mins[node], c[node][*it] - flow[node][*it]);
      if (*it == stop)
        return true;
      q.push(*it);
    }
  }

  return false;
}


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);
    nodes[y].push_back(x);
  }

  int start = 1, stop = n;
  bool found_path = true;
  int max_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]);
      max_flow += mins[stop];
      while (node != start) {
        DBG(node);
        flow[previous[node]][node] += mins[stop];
        flow[node][previous[node]] -= mins[stop];
        node = previous[node];
      }
      DBG(max_flow);
      //      print_c();
    }
  }

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