Cod sursa(job #1827358)

Utilizator cella.florescuCella Florescu cella.florescu Data 11 decembrie 2016 19:24:01
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.58 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 351;
const int INF = 0x3f3f3f3f;

vector <int> g[MAXN];
queue <int> q;
int flow[MAXN][MAXN], cap[MAXN][MAXN], cost[MAXN][MAXN];
int father[MAXN], inq[MAXN], old_dist[MAXN], dijk_dist[MAXN], real_dist[MAXN];

int bellman(int s, int d) {
  int node;
  memset(old_dist, INF, sizeof old_dist);
  inq[s] = 1;
  old_dist[s] = 0;
  q.push(s);
  while (q.empty() == 0) {
    node = q.front();
    inq[node] = 0;
    q.pop();
    for (auto it : g[node])
      if (flow[node][it] < cap[node][it] && old_dist[it] > old_dist[node] + cost[node][it]) {
        old_dist[it] = old_dist[node] + cost[node][it];
        father[it] = node;
        if (inq[it] == 0) {
          inq[it] = 1;
          q.push(it);
        }
      }
  }
  return (old_dist[d] < INF);
}

struct PQNode {
  int node, cost;
  bool operator < (const PQNode &other) const {
    return cost > other.cost;
  }
};

priority_queue <PQNode> pq;

int dijkstra(int s, int d) {
  int aux, cst, nod;
  memset(dijk_dist, INF, sizeof dijk_dist);
  real_dist[s] = dijk_dist[s] = 0;
  pq.push({s, 0});
  while (pq.empty() == 0) {
    nod = pq.top().node;
    cst = pq.top().cost;
    pq.pop();
    if (cst == dijk_dist[nod])
      for (auto it : g[nod]) {
        aux = dijk_dist[nod] + cost[nod][it] + old_dist[nod] - old_dist[it];
        if (flow[nod][it] < cap[nod][it] && dijk_dist[it] > aux) {
          father[it] = nod;
          dijk_dist[it] = aux;
          real_dist[it] = real_dist[nod] + cost[nod][it];
          pq.push({it, aux});
        }
      }
  }
  memcpy(old_dist, real_dist, sizeof old_dist);
  return (dijk_dist[d] < INF);
}

inline int minimum(int A, int B) {
  if (A < B)
    return A;
  return B;
}

int main()
{
    int n, m, s, d, x, y, c, z, node, fl, ans;
    ifstream fin("fmcm.in");
    fin >> n >> m >> s >> d;
    for (int i = 0; i < m; ++i) {
      fin >> x >> y >> c >> z;
      g[x].push_back(y);
      g[y].push_back(x);
      cap[x][y] = c;
      cost[x][y] = z;
      cost[y][x] = -z;
    }
    fin.close();
    ans = 0;
    bellman(s, d);
    while (dijkstra(s, d)) {
      for (fl = INF, node = d; node != s; node = father[node])
        fl = minimum(fl, cap[father[node]][node] - flow[father[node]][node]);
      for (node = d; node != s; node = father[node]) {
        flow[father[node]][node] += fl;
        flow[node][father[node]] -= fl;
      }
      ans += fl * real_dist[d];
    }
    ofstream fout("fmcm.out");
    fout << ans << '\n';
    fout.close();
    return 0;
}