Cod sursa(job #3193392)

Utilizator pifaDumitru Andrei Denis pifa Data 14 ianuarie 2024 15:31:12
Problema Flux maxim de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.62 kb
#include <bits/stdc++.h>
#define pragma ("O3")
#define pragma ("Ofast")

using namespace std;

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

int n, m, s, t;

const int N = 355;

vector <int> g[N];

int cap[N][N], cost[N][N], dist[N], viz[N];

const int INF = 1e9;

void bellman()
{
    for(int i = 1; i <= n; i++)
        dist[i] = INF;
    queue <int> q;
    q.push(s);
    dist[s] = 0;
    while(q.size())
    {
        int cur = q.front();
        q.pop();
        for(auto next:g[cur])
        {
            if(cap[cur][next] > 0 && (dist[next] > dist[cur] + cost[cur][next]))
            {
                dist[next] = dist[cur] + cost[cur][next];
                q.push(next);
            }
        }
    }
}

struct cmp
{
    bool operator()(pair <int, int> a, pair <int, int> b)
    {
        return a.first> b.first;
    }
};

int dijk[N], d[N], pred[N];
int max_flux_min_cost;
bool dijkstra(int s, int t)
{
    for(int i = 1; i <= n; i++)
    {
        dijk[i] = INF;
        d[i] = INF;
        viz[i] = 0;
        pred[i] = 0;
    }
    d[s] = 0;
    dijk[s] = 0;
    priority_queue <pair <int, int>, vector <pair< int, int>>, cmp> pq;
    pq.push({0, s});
    while(pq.size())
    {
        int cur = pq.top().second;
        pq.pop();
        if(viz[cur])
            continue;
        viz[cur] = 1;
        for(auto next:g[cur])
        {
            if(cap[cur][next] > 0 && d[next] > d[cur] + cost[cur][next] + dist[cur] - dist[next])
            {
                d[next] = d[cur] + cost[cur][next] + dist[cur] - dist[next];
                dijk[next] = dijk[cur] + cost[cur][next];
                pred[next] = cur;
                pq.push({d[next], next});
            }
        }
    }
    for(int i = 1; i <= n; i++)
        dist[i] = d[i];
    if(dijk[t] == INF)
        return 0;
    int minim = INF;
    for(int i = t; i != s; i = pred[i])
        minim = min(minim, cap[pred[i]][i]);
    max_flux_min_cost += minim * dijk[t];
    for(int i = t; i != s; i = pred[i])
    {
        cap[pred[i]][i] -= minim;
        cap[i][pred[i]] += minim;
    }
    return 1;
}

int32_t main()
{
    ios_base::sync_with_stdio(false);
    in.tie(0);
    in >> n >> m >> s >> t;
    for(int i = 1; i <= m; i++)
    {
        int x, y, capacitate, c;
        in >> x >> y >> capacitate >> c;
        g[x].push_back(y);
        g[y].push_back(x);
        cap[x][y] = capacitate;
        cost[x][y] = c;
        cost[y][x] = -c;
    }
    bellman();
    while(dijkstra(s, t));
    out << max_flux_min_cost;
    in.close();
    out.close();
    return 0;
}