Cod sursa(job #578707)

Utilizator mottyMatei-Dan Epure motty Data 11 aprilie 2011 15:21:47
Problema Flux maxim de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <queue>

using namespace std;

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

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

int n, s, d;
int fat[N];
int best[N];
int flow[N][N];
int cost[N][N];
int capc[N][N];

void Read()
{
  int m;
  in >> n >> m >> s >> d;

  while (m--)
  {
    int a, b, cap, price;
    in >> a >> b >> cap >> price;

    capc[a][b] = cap;
    cost[a][b] = price;
    cost[b][a] = -price;
  }
}

bool Road()
{
  queue <int> q;
  memset(best, INF, sizeof(best));

  q.push(s);
  best[s] = 0;

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

    for (int i = 1; i <= n; ++i)
      if (capc[node][i] - flow[node][i] > 0
        && best[node] + cost[node][i] < best[i])
      {
        best[i] = best[node] + cost[node][i];
        fat[i] = node;

        q.push(i);
      }

    q.pop();
  }

  return (best[d] != INF);
}

int GetMaxFlow()
{
  int totalCost = 0;

  while (Road())
  {
    int node = d;
    int minFlow = INF;

    while (node != s)
    {
      if (capc[fat[node]][node] - flow[fat[node]][node] < minFlow)
        minFlow = capc[fat[node]][node] - flow[fat[node]][node];

      node = fat[node];
    }

    node = d;

    while (node != s)
    {
      flow[fat[node]][node] += minFlow;
      flow[node][fat[node]] -= minFlow;

      totalCost += minFlow * cost[fat[node]][node];

      node = fat[node];
    }
  }

  return totalCost;
}

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

  return 0;
}