Cod sursa(job #2358016)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 27 februarie 2019 20:53:32
Problema Flux maxim de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <vector>
#include <deque>

using namespace std;

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

const int NMAX = 360;
const int INF = 2000000000;

int N, M;
int source, sink;

vector <int> Ad[NMAX];

int flow[NMAX][NMAX];
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
int parent[NMAX];

void Read()
{
  fin >> N >> M;
  fin >> source >> sink;

  int x, y, c, lei;

  for( int i = 1; i <= M; ++i )
  {
    fin >> x >> y >> c >> lei;

    Ad[x].push_back(y);
    Ad[x].push_back(x);

    cap[x][y] = c;
    cost[x][y] = lei;
    cost[y][x] = -lei;
  }

  fin.close();
}

bool Bf()
{
   deque <int> Q;

   int d[NMAX];
   bool in_q[NMAX] = { 0 };

   for( int i = 1; i <= NMAX; ++i )
    d[i] = INF,
    parent[i] = 0;

   d[source] = 0;
   Q.push_back( source );

   in_q[source] = true;

   int w, u;
   int mzg = 0;

   while( !Q.empty() )
   {
     u = Q.front();
     Q.pop_front();

     in_q[u] = 0;

     for( int i = 0; i < Ad[u].size(); ++i )
     {
       w = Ad[u][i];

       if( cap[u][w] - flow[u][w] > 0 && d[w] > d[u] + cost[u][w] )
       {
         d[w] = d[u] + cost[u][w];

         parent[w] = u;

         if( !in_q[w] )
         {
           Q.push_back( w );
           in_q[w] = true;
         }
       }
     }
   }

  if( d[sink] == INF ) return false;
  else return true;
}

void Do()
{
  int cost_total = 0;
  int curent_flow;

  while( Bf() )
  {
    curent_flow = INF;

  //  if( parent[sink] == 0 ) continue;

    for( int nod = sink; nod != source; nod = parent[nod] )
      curent_flow = min( curent_flow, cap[ parent[nod] ][nod] - flow[ parent[nod] ][ nod ] );

    for( int nod = sink; nod != source; nod = parent[nod] )
    {
      flow[ parent[nod]][ nod ] += curent_flow;
      flow[ nod ][ parent[nod]] -= curent_flow;

      cost_total += curent_flow * cost[ parent[nod] ][nod];
    }
  }

  fout << cost_total << '\n';
}

int main()
{
   Read();
   Do();

    return 0;
}