Cod sursa(job #1162924)

Utilizator Ionut228Ionut Calofir Ionut228 Data 1 aprilie 2014 01:52:30
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

const int INF = 0x3f3f3f3f;

int N, M, S, D;
int maxCost, flow, flow_min;
int C[352][352], F[352][352], Father[352];
vector<pair<int, int> > V[352];
queue<int> Q;
int Dmin[352];
bool inQ[352];

int bellman_ford()
{
    memset(Dmin, INF, sizeof(Dmin));
    memset(inQ, false, sizeof(inQ));
    Dmin[S] = 0;
    Q.push(S);
    inQ[S] = true;

    while (!Q.empty())
    {
        int now = Q.front();
        Q.pop();
        inQ[now] = false;

        if (now == D)
            continue;
        for (vector<pair<int, int> >::iterator it = V[now].begin(); it != V[now].end(); ++it)
        {
            if (C[now][it->first] == F[now][it->first])
                continue;
            if (Dmin[now] + it->second < Dmin[it->first])
            {
                Dmin[it->first] = Dmin[now] + it->second;
                Father[it->first] = now;
                if (!inQ[it->first])
                {
                    inQ[it->first] = true;
                    Q.push(it->first);
                }
            }
        }
    }

    return (Dmin[D] != INF);
}

int main()
{
    fin >> N >> M >> S >> D;
    for (int i = 1, nod1, nod2, flux, cost; i <= M; ++i)
    {
        fin >> nod1 >> nod2 >> flux >> cost;
        C[nod1][nod2] += flux;
        V[nod1].push_back(make_pair(nod2, cost));
        V[nod2].push_back(make_pair(nod1, -cost));
    }

    while (bellman_ford())
    {
        flow_min = INF;
        for (int nod = D; nod != S; nod = Father[nod])
            flow_min = min(flow_min, C[Father[nod]][nod] - F[Father[nod]][nod]);
        if (flow_min == 0)
            continue;

        for (int nod = D; nod != S; nod = Father[nod])
        {
            F[Father[nod]][nod] += flow_min;
            F[nod][Father[nod]] -= flow_min;
        }

        flow += flow_min;
        maxCost += flow_min * Dmin[D];
    }

    fout << maxCost << '\n';

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