Cod sursa(job #2722020)

Utilizator Marius7122FMI Ciltea Marian Marius7122 Data 12 martie 2021 15:53:54
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int INF = 1e9;
const int N = 355;

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

int n, m, source, sink, fmax, cmin;
int cap[N][N], flow[N][N];
vector<pair<int, int>> g[N];
vector<int> t, dist;

void BellmanFordCoada(int s)
{
    dist.assign(n + 1, INF);
    vector<bool> inCoada(n + 1);
    t.assign(n + 1, 0);
    dist[s] = 0;

    queue<int> q;
    q.push(s);
    inCoada[s] = true;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        inCoada[x] = false;

        for(auto neigh : g[x])
        {
            int y = neigh.first;
            int cost = neigh.second;

            if(flow[x][y] != cap[x][y] && dist[x] + cost < dist[y])
            {
                dist[y] = dist[x] + cost;
                t[y] = x;
                if(!inCoada[y])
                {
                    q.push(y);
                    inCoada[y] = true;
                }
            }
        }
    }
}

int maxFlowMinCost()
{
    fmax = 0;
    cmin = 0;
    do
    {
        BellmanFordCoada(source);


        if(dist[sink] == INF)
            break;

        int fmin = 1 << 30;
        for(int node = sink; node != source; node = t[node])
            fmin = min(fmin, cap[t[node]][node] - flow[t[node]][node]);

        if(fmin == 0)
            continue;

        fmax += fmin;
        cmin += dist[sink] * fmin;
        for(int node = sink; node != source; node = t[node])
        {
            flow[t[node]][node] += fmin;
            flow[node][t[node]] -= fmin;
        }
    } while(dist[sink] != INF);

    return cmin;
}

int main()
{
    fin >> n >> m >> source >> sink;
    for(int i = 0; i < m; i++)
    {
        int x, y, c, cost;
        fin >> x >> y >> c >> cost;
        g[x].push_back({y, cost});
        g[y].push_back({x, -cost});
        cap[x][y] = c;
    }

    fout << maxFlowMinCost() << '\n';


    return 0;
}