Cod sursa(job #3155928)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 10 octombrie 2023 10:58:42
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.69 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int max_size = 351, INF = 2e9 + 1;

struct str{
    int nod, cost;
    bool operator < (const str & aux) const
    {
        return cost > aux.cost;
    }
};

int cap[max_size][max_size], cost[max_size][max_size], dist[max_size], pr[max_size], aux[max_size], t[max_size], n;
vector <int> mc[max_size];
priority_queue <str> pq;
queue <int> q;

void bf (int s)
{
    for (int i = 1; i <= n; i++)
    {
        aux[i] = INF;
    }
    aux[s] = 0;
    q.push(s);
    while (!q.empty())
    {
        int nod = q.front();
        dist[nod] = 0;
        q.pop();
        for (auto f : mc[nod])
        {
            if (cap[nod][f] > 0 && aux[nod] + cost[nod][f] < aux[f])
            {
                aux[f] = aux[nod] + cost[nod][f];
                if (dist[f] == 0)
                {
                    dist[f] = 1;
                    q.push(f);
                }
            }
        }
    }
}

bool djk (int src, int dest)
{
    for (int i = 1; i <= n; i++)
    {
        dist[i] = INF;
        pr[i] = INF;
        t[i] = 0;
    }
    dist[src] = 0;
    pr[src] = 0;
    pq.push({src, 0});
    while (!pq.empty())
    {
        int nod = pq.top().nod, val = pq.top().cost;
        pq.pop();
        if (val > dist[nod])
        {
            continue;
        }
        for (auto f : mc[nod])
        {
            if (cap[nod][f] > 0 && dist[nod] + cost[nod][f] + aux[nod] - aux[f] < dist[f])
            {
                dist[f] = dist[nod] + cost[nod][f] + aux[nod] - aux[f];
                pr[f] = pr[nod] + cost[nod][f];
                t[f] = nod;
                pq.push({f, dist[f]});
            }
        }
    }
    return (dist[dest] != INF);
}

int main ()
{
    int m, s, d;
    in >> n >> m >> s >> d;
    while (m--)
    {
        int x, y, fl, c;
        in >> x >> y >> fl >> c;
        mc[x].push_back(y);
        mc[y].push_back(x);
        cap[x][y] += fl;
        cost[x][y] = c;
        cost[y][x] = -c;
    }
    bf(s);
    int ans = 0;
    while (djk(s, d))
    {
        int nod = d, mn = INF;
        while (nod != s)
        {
            mn = min(mn, cap[t[nod]][nod]);
            nod = t[nod];
        }
        ans += pr[d] * mn;
        nod = d;
        while (nod != s)
        {
            cap[t[nod]][nod] -= mn;
            cap[nod][t[nod]] += mn;
            nod = t[nod];
        }
        for (int i = 1; i <= n; i++)
        {
            aux[i] = dist[i];
        }
    }
    out << ans;
    in.close();
    out.close();
    return 0;
}