Cod sursa(job #2961931)

Utilizator crivoicarlaCrivoi Carla crivoicarla Data 7 ianuarie 2023 13:55:15
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.92 kb
//
// Created by Carla on 1/7/2023.
//
#include <iostream>

#include <vector>

#include <queue>

#include <cstring>

#include <fstream>

#include <algorithm>



using namespace std;



ifstream in("fmcm.in");

ofstream out("fmcm.out");



int n, m, src, dest, flux = 0, cost_flux = 0;

vector<int> l[355];

int cst[355][355], cap[355][355];

int tata[355], coada[355], dist_bf[355], dist_d[355], dist[355];

queue<int> q;

priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;



void bellman_ford()

{

    memset(dist_bf, 0x3f, sizeof(dist_bf));



    dist_bf[src] = 0;

    q.push(src);

    coada[src] = 1;



    while(!q.empty())

    {

        int x = q.front();

        coada[x] = 0;

        q.pop();

        for(auto it: l[x])

        {

            if(cap[x][it])

            {

                if(dist_bf[x] + cst[x][it] < dist_bf[it])

                {

                    dist_bf[it] = dist_bf[x] + cst[x][it];

                    if(!coada[it])

                    {

                        coada[it] = 1;

                        q.push(it);

                    }

                }

            }

        }

    }

}



int dijkstra()

{

    memset(dist, 0x3f, sizeof(dist));

    dist[src] = 0;

    dist_d[src] = 0;



    pq.push(make_pair(dist[src], src));



    while(!pq.empty())

    {

        int c = pq.top().first, x = pq.top().second;

        pq.pop();

        if(dist[x] == c)

        {

            for(auto it: l[x])

            {

                if(cap[x][it] > 0)

                {

                    if(dist[x] + cst[x][it] + dist_bf[x] - dist_bf[it] < dist[it])

                    {

                        dist[it] = dist[x] + cst[x][it] + dist_bf[x] - dist_bf[it];

                        dist_d[it] = dist_d[x] + cst[x][it];

                        tata[it] = x;

                        pq.push(make_pair(dist[it], it));

                    }

                }



            }

        }

    }

    memcpy(dist_bf, dist_d, sizeof(dist));

    if(dist[dest] == 0x3f3f3f3f)
        return 0;

    int minim = 0x3f3f3f3f;

    for(int i = dest; i != src; i = tata[i])
    {
        int j = tata[i];
        minim = min(minim, cap[j][i]);
    }

    for(int i = dest; i != src; i = tata[i])
    {
        int j = tata[i];
        cap[i][j] += minim;
        cap[j][i] -= minim;
    }
    cost_flux += minim * dist_d[dest];
    return 1;

}



int main()
{
    int x, y, ct, cp, bf;
    in>>n>>m>>src>>dest;
    for(int i =1; i <= m; i++)
    {
        in>>x>>y>>cp>>ct;
        l[x].push_back(y);
        l[y].push_back(x);
        cap[x][y] = cp;
        cst[x][y] = ct;
        cst[y][x] = -ct;
    }

    bellman_ford();
    while(dijkstra());
    out<<cost_flux;

    return 0;

}