Cod sursa(job #989772)

Utilizator toranagahVlad Badelita toranagah Data 26 august 2013 14:16:44
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

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

const int MAX_N = 1005;
const int INF = 1 << 30;

int N, M;
vector<int> graph[MAX_N];
int residual_capacity[MAX_N][MAX_N];
int incoming[MAX_N];
int dist[MAX_N];
int source, sink;

void read_input();
int maxflow();
bool find_augmenting_path();

int main() {
  read_input();
  fout << maxflow();
}

void read_input() {
  fin >> N >> M;
  for (int i = 1, a, b, c; i <= M; ++i) {
    fin >> a >> b >> c;
    graph[a].push_back(b);
    graph[b].push_back(a);
    residual_capacity[a][b] = c;
  }
  source = 1;
  sink = N;
}

int maxflow() {
  int result = 0;
  while (find_augmenting_path()) {
    int flow = INF;
    for (int node = sink; node != source; node = incoming[node]) {
      flow = min(flow, residual_capacity[incoming[node]][node]);
    }
    result += flow;
    
    for (int node = sink; node != source; node = incoming[node]) {
      residual_capacity[incoming[node]][node] -= flow;
      residual_capacity[node][incoming[node]] += flow;
    }
  }
  return result;
}

bool find_augmenting_path() {
  fill(dist + 1, dist + N + 1, INF);
  queue<int> q;
  q.push(source);
  dist[source] = 0;

  while (!q.empty()) {
    int node = q.front();
    q.pop();

    for (auto next : graph[node]) {
      if (residual_capacity[node][next] > 0) {
        if (dist[node] + 1 < dist[next]) {
          dist[next] = dist[node] + 1;
          incoming[next] = node;
          q.push(next);

          if (next == sink) return true;
        }
      }
    }
  }
  return false;
}