Cod sursa(job #567939)

Utilizator mottyMatei-Dan Epure motty Data 30 martie 2011 17:10:48
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <queue>

using namespace std;

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

const int N = 1001;
const int INF = 0x3f3f3f;

int n;
int c[N][N];
int f[N][N];
int fat[N];

bool viz[N];

void Read()
{
  int m;

  in >> n >> m;

  while (m--)
  {
    int a, b, cost;

    in >> a >> b >> cost;

    c[a][b] = cost;
  }
}

//fac bfs

bool Bfs()
{
  memset(viz, 0, sizeof(viz));
  viz[1] = true;

  queue <int> q;

  q.push(1);

  while (!q.empty() && !viz[n])
  {
    int node = q.front();

    for (int i = 1; i <= n; ++i)
      if (!viz[i] && f[node][i] < c[node][i])
      {
        q.push(i);

        viz[i] = true;
        fat[i] = node;
      }

    q.pop();
  }

  return viz[n];
}

int GetMaxFlow()
{
  int result = 0;

  while (Bfs())
  {
    int node = n;
    int minFlow = INF;

    while (node != 1)
    {
      minFlow = min(minFlow, c[fat[node]][node] - f[fat[node]][node]);

      node = fat[node];
    }

    node = n;

    while (node != 1)
    {
      f[fat[node]][node] += minFlow;
      f[node][fat[node]] -= minFlow;

      node = fat[node];
    }

    result += minFlow;
  }

  return result;
}

int main()
{
  Read();
  out << GetMaxFlow() << "\n";

  return 0;
}