Cod sursa(job #1214650)

Utilizator OwlreeRobert Badea Owlree Data 31 iulie 2014 00:41:59
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1024;

int  graph[NMAX][NMAX];
int  resid[NMAX][NMAX];
int  shptr[NMAX];
bool vistd[NMAX];
int N, M;

int pfs()
{
  // 1 -> N;
  priority_queue <pair <int, int> > pq;
  pq.push(make_pair(INT_MAX, 1));
  memset(vistd, false, sizeof(vistd));

  while (!pq.empty()) {
    int magp = pq.top().first;
    int node = pq.top().second;

    pq.pop();

    if (node == N) {
      return magp;
    }

    vistd[node] = true;
    for (int i = 1; i <= N; ++i) {
      if (resid[node][i] > 0) {
        if (!vistd[i]) {
          pq.push(make_pair(min(magp, resid[node][i]), i));
          shptr[i] = node;
        }
      }
    }
  }

  return 0;
}

int main()
{
  ifstream  in("maxflow.in");
  ofstream out("maxflow.out");

  in >> N >> M;

  for (int a, b, c, i = 0; i < M; ++i) {
    in >> a >> b >> c;
    graph[a][b] = c;
  }

  for (int i = 1; i <= N; ++i) {
    for (int j = i; j <= N; ++j) {
      if (graph[i][j] > 0) {
        resid[i][j] = graph[i][j];
        resid[j][i] = 0;
      } else {
        resid[i][j] = -1;
        resid[j][i] = -1;
      }
    }
  }

  int a = 0;
  int flow = 0;

  while ((a = pfs()) > 0) {
    flow += a;
    int x = N;
    while (x != 1) {
      x = shptr[x];
      resid[shptr[x]][x] -= a;
      resid[x][shptr[x]] += a;
    }
  }

  out << flow << "\n";

  return 0;
}