Cod sursa(job #2629895)

Utilizator popashtefan10Popa Stefan popashtefan10 Data 23 iunie 2020 10:50:52
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 350;
const int MMAX = 12500;
const int FMAX = 1000000000;
const int CMAX = 1000000000;

struct muchie {
  int a, b;       /// a -> inceput, b -> sfarsit
  int cf, cost;   /// capacitate - flux, costul muchiei

  muchie(int ca = 0, int cb = 0, int ccf = 0, int ccost = 0) : a(ca), b(cb), cf(ccf), cost(ccost) {}
};

struct elem {
  int nod, cost, idx; /// idx - indicele muchiei prin care se ajunge la nod
  elem(int cnod = 0, int ccost = 0, int cidx = 0) : nod(cnod), cost(ccost), idx(cidx) {}
};

bool operator > (elem e1, elem e2) {
  return e1.cost > e2.cost;
}

int n, m, s, d, ctot;
int from[NMAX + 5];
int mind[NMAX + 5];

muchie muchii[MMAX * 2 + 5];
vector<int> v[NMAX + 5];
priority_queue<elem, vector<elem>, greater<elem>> pq;

bool dijkstra(int start) {
  bool vizd = false;

  while(!pq.empty())
    pq.pop();
  for(int i = 1; i <= n; i++) {
    mind[i] = CMAX;
    from[i] = -1;
  }

  pq.push(elem(start, 0, -1));
  mind[start] = 0;

  while(!pq.empty()) {
    elem crt = pq.top();
    pq.pop();
    if(crt.cost > mind[crt.nod])
      continue;
    if(crt.nod == d) {
      vizd = true;
      continue;
    }

    for(int vec: v[crt.nod]) {
      muchie &mvec = muchii[vec];

      if(mvec.cf > 0 && crt.cost + mvec.cost < mind[mvec.b]) {
        pq.push(elem(mvec.b, crt.cost + mvec.cost, vec));
        mind[mvec.b] = crt.cost + mvec.cost;
        from[mvec.b] = vec;
      }
    }
  }

  return vizd;
}

void add_flux() {
  int nod = d, fmin = FMAX;

  while(from[nod] != -1) {
    fmin = min(fmin, muchii[from[nod]].cf);
    nod = muchii[from[nod]].a;
  }

  ctot += fmin * mind[d];
  nod = d;
  while(from[nod] != -1) {
    muchii[from[nod]].cf -= fmin;
    muchii[from[nod] ^ 1].cf += fmin;
    nod = muchii[from[nod]].a;
  }
}

int main() {
  freopen("fmcm.in", "r", stdin);
  freopen("fmcm.out", "w", stdout);

  scanf("%d %d %d %d", &n, &m, &s, &d);
  for(int i = 0; i < m; i++) {
    int x, y, z, t;

    scanf("%d %d %d %d", &x, &y, &z, &t);
    muchii[2 * i] = muchie(x, y, z, t);
    muchii[2 * i + 1] = muchie(y, x, 0, -t);

    v[x].push_back(2 * i);
    v[y].push_back(2 * i + 1);
  }

  while(dijkstra(s))
    add_flux();

  printf("%d", ctot);

  return 0;
}