Cod sursa(job #3125932)

Utilizator raulandreipopRaul-Andrei Pop raulandreipop Data 4 mai 2023 20:04:03
Problema Flux maxim de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
const int nmax = 350 , mmax = 12500;
const int inf = 1e9;
int n, m, s, d;
int add;

struct edge {
    int cost;
    int r , cap;
    int av ()
    {
        return cap - r;
    }
};

vector<edge> e[nmax+1][nmax+1];
pair<int , int> p[nmax+1];

bool bellman ()
{
    
    priority_queue<pair<int , int> , vector<pair<int , int>> , greater<pair<int , int>> > q;
    q.push({0 , s});
    vector<int> dist(n+1 , inf);
    dist[s] = 0;
    while (q.size())
    {
        int nod = q.top().second;
        int cost = q.top().first;
        q.pop();
        add = dist[d];
        if (nod == d) return 1;
        if (cost > dist[nod]) continue;
        for (int to = 1; to <= n; to++)
        {
            for (int i = 0; i < e[nod][to].size(); i++)
            {
                edge edg = e[nod][to][i];
                if (edg.r == edg.cap) continue;
                if (cost + edg.cost < dist[to])
                {
                    dist[to] = cost + edg.cost;
                    p[to] = {nod, i};
                    q.push({dist[to] , to});
                }
            }
        }
    }
    return 0;
}

int main ()
{
    freopen("fmcm.in" , "r" , stdin);
    freopen("fmcm.out" , "w" , stdout);
    cin >> n >> m >> s >> d;
    for (int i = 1; i <= m; i++)
    {
        int x , y , c , z;
        cin >> x >> y >> c >> z;
        e[x][y].push_back({z , 0 , c});
        e[y][x].push_back({-z, 0 , 0});
    }

    int fluxTotal = 0;
    int answer = 0;
    while (bellman())
    {
        int nod = d;
        int flow = inf;
        while (nod != s)
        {
            int ind = p[nod].second , pnod = p[nod].first;
            flow = min(flow , e[pnod][nod][ind].av());
            nod = pnod;
        }
        nod = d;
        while (nod != s)
        {
            int ind = p[nod].second , pnod = p[nod].first;
            e[pnod][nod][ind].r += flow;
            nod = pnod;
        }
        fluxTotal += flow;
        answer += add * flow;
     //   cout << add << ' ' << flow << '\n';
    }
    cout << answer << '\n';
}