Cod sursa(job #2550105)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 18 februarie 2020 14:07:56
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 350;
const int INF = 20000000;

int N, M, S, D;

vector <int> g[NMAX + 5];

int capacity[NMAX + 5][NMAX + 5], flow[NMAX + 5][NMAX + 5];
int cost[NMAX + 5][NMAX + 5];

bool seen[NMAX + 5];
int costTo[NMAX + 5], bef[NMAX + 5];

bool BellmanFord()
{
    for(int i = 1; i <= N; i++)
        costTo[i] = INF;

    queue <int> Q;

    Q.push(S);
    costTo[S] = 0;
    seen[S] = 1;

    while(!Q.empty())
    {
        int node = Q.front();
        Q.pop();

        seen[node] = 0;

        for(auto it : g[node])
            if(flow[node][it] < capacity[node][it])
                if(costTo[it] > costTo[node] + cost[node][it])
                {
                    costTo[it] = costTo[node] + cost[node][it];
                    bef[it] = node;

                    if(seen[it] == 0)
                    {
                        seen[it] = 1;
                        Q.push(it);
                    }
                }
    }

    return costTo[D] != INF;
}

int main()
{
    fin >> N >> M >> S >> D;

    for(int i = 1; i <= M; i++)
    {
        int x, y, cap, cst;
        fin >> x >> y >> cap >> cst;

        g[x].push_back(y);
        g[y].push_back(x);

        capacity[x][y] = cap;

        cost[x][y] = cst;
        cost[y][x] = -cst;
    }

    int ans = 0;

    while(BellmanFord())
    {
        int pumpFlow = capacity[bef[D]][D] - flow[bef[D]][D];

        for(int i = D; i != S; i = bef[i])
            pumpFlow = min(pumpFlow, capacity[bef[i]][i] - flow[bef[i]][i]);

        for(int i = D; i != S; i = bef[i])
        {
            flow[bef[i]][i] += pumpFlow;
            flow[i][bef[i]] -= pumpFlow;
        }

        ans += pumpFlow * costTo[D];
    }

    fout << ans << '\n';

    return 0;
}