Cod sursa(job #1556268)

Utilizator andreiiiiPopa Andrei andreiiii Data 24 decembrie 2015 14:08:08
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <algorithm>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;

const int NMAX = 355, INF = 0x3f3f3f3f;
vector<int> G[NMAX];
int C[NMAX][NMAX], F[NMAX][NMAX], cost[NMAX][NMAX];
int dist[NMAX], father[NMAX];
bool inQueue[NMAX];

bool bellmanFord(int s, int d) {
    memset(dist, INF, sizeof dist);
    memset(father, -1, sizeof father);
    memset(inQueue, 0, sizeof inQueue);
    father[s] = -2;
    dist[s] = 0;
    queue<int> q;
    q.push(s);

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        inQueue[node] = false;

        for (int p: G[node]) {
            if (dist[p] > dist[node] + cost[node][p] &&
                    C[node][p] > F[node][p]) {
                dist[p] = dist[node] + cost[node][p];
                father[p] = node;
                if (!inQueue[p]) {
                    q.push(p);
                    inQueue[p] = true;
                }
            }
        }
    }
    return father[d] != -1;
}

int getFlow(int s, int d) {
    int flow = 0, cost = 0;
    while (bellmanFord(s, d)) {
        int fmin = INF;
        for (int i = d; i != s; i = father[i])
            fmin = min(fmin, C[father[i]][i] - F[father[i]][i]);
        flow += fmin;
        cost += fmin * dist[d];
        for (int i = d; i != s; i = father[i]) {
            F[father[i]][i] += fmin;
            F[i][father[i]] -= fmin;
        }
    }
    return cost;
}

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

    int n, m, s, d;
    fin >> n >> m >> s >> d;

    for (int i = 0; i < m; ++i) {
        int x, y, cap, c;
        fin >> x >> y >> cap >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] = cap;
        cost[x][y] = c;
        cost[y][x] = -c;
    }

    int flow = getFlow(s, d);
    fout << flow << '\n';

    fin.close();
    fout.close();
}