Cod sursa(job #1971333)

Utilizator Andrei1998Andrei Constantinescu Andrei1998 Data 20 aprilie 2017 12:05:34
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <fstream>
#include <vector>
#include <queue>

//11:40 47 58
using namespace std;

const int NMAX = 350 + 5;
const int MMAX = 12500 + 5;
const int INF = 1E9;

int N, M, S, T;
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
vector <int> graph[NMAX];

bool inQueue[NMAX];
queue <int> q;
int dist[NMAX];
int father[NMAX];

bool BF() {
    while (!q.empty())
        q.pop();
    for (int i = 1; i <= N; ++ i)
        dist[i] = INF, father[i] = inQueue[i] = 0;

    q.push(S);
    dist[S] = 0;
    inQueue[S] = true;

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

        if (node == T)
            return true;

        for (auto it: graph[node])
            if (cap[node][it] && dist[node] + cost[node][it] < dist[it]) {
                dist[it] = dist[node] + cost[node][it];
                father[it] = node;
                if (!inQueue[it]) {
                    inQueue[it] = true;
                    q.push(it);
                }
            }
    }

    return false;
}

int _flow, _cost;
int minCostFlow() {
    int ans = 0;
    while (BF()) {
        int node = T;
        int f = INF;
        while (node != S) {
            f = min(f, cap[father[node]][node]);
            node = father[node];
        }

        node = T;
        while (node != S) {
            cap[father[node]][node] -= f;
            cap[node][father[node]] += f;
            ans += cost[father[node]][node] * f;
            node = father[node];
        }
    }

    return ans;
}

int main()
{
    ifstream cin("fmcm.in");
    ofstream cout("fmcm.out");

    cin >> N >> M >> S >> T;

    for (int i = 1; i <= M; ++ i) {
        int a, b, c, d;
        cin >> a >> b >> c >> d;
        cap[a][b] += c;
        cost[a][b] += d;
        cost[b][a] -= d;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    cout << minCostFlow() << '\n';
    return 0;
}