Cod sursa(job #2420226)

Utilizator Coroian_DavidCoroian David Coroian_David Data 11 mai 2019 11:38:52
Problema Flux maxim de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.75 kb
#include <bits/stdc++.h>

#define MAX_N 350

using namespace std;

const int sqrInf = (int)(1e9) + 7;

int rez;

int tata[MAX_N + 1];

int n, m;
int s, d;

vector <int> g[MAX_N + 1];

int c[MAX_N + 1][MAX_N + 1];
int cost[MAX_N + 1][MAX_N + 1];

int dist[MAX_N + 1];
int dp[MAX_N + 1];
int good[MAX_N + 1];

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

void add(int a, int b)
{
    g[a].push_back(b);
}

void readFile()
{
    ifstream f("fmcm.in");

    f >> n >> m >> s >> d;

    int x, y;
    for(int i = 1; i <= m; i ++)
    {
        f >> x >> y;
        add(x, y);
        f >> c[x][y] >> cost[x][y];

        cost[y][x] = -cost[x][y];
    }

    f.close();
}

queue <int> q;
bool inQue[MAX_N + 1];

void bellman()
{
    for(int i = 1; i <= n; i ++)
        dist[i] = sqrInf;

    dist[s] = 0;

    q.push(s);
    while(q.size() > 0)
    {
        int cr = q.front();
        q.pop();
        inQue[cr] = 0;

        for(auto u : g[cr])
        {
            if(c[cr][u] != 0)
            {
                if(dist[cr] + cost[cr][u] < dist[u])
                {
                    dist[u] = dist[cr] + cost[cr][u];

                    if(inQue[u] == 0)
                    {
                        inQue[u] = 1;
                        q.push(u);
                    }
                }
            }
        }
    }
}

bool distra()
{
    for(int i = 1; i <= n; i ++)
        dp[i] = sqrInf;

    dp[s] = good[s] = 0;
    H.push({dp[s], s});

    while(H.size() > 0)
    {
        int cr = H.top().second;
        int x = H.top().first;

        H.pop();

        if(dp[cr] != x)
            continue;

        for(auto u : g[cr])
        {
            if(c[cr][u] != 0)
            {
                int dst = dp[cr] + cost[cr][u] + dist[cr] - dist[u];
                if(dst < dp[u])
                {
                    dp[u] = dst;
                    H.push({dst, u});
                    tata[u] = cr;
                    good[u] = good[cr] + cost[cr][u];
                }
            }
        }
    }

    for(int i = 1; i <= n; i ++)
        dist[i] = good[i];

    if(dp[d] == sqrInf)
        return 0;

    int mn = sqrInf, ccr = 0;
    for(int i = d; i != s; i = tata[i])
        mn = min(mn, c[tata[i]][i]);

    rez += mn * good[d];
    for(int i = d; i != s; i = tata[i])
    {
        c[tata[i]][i] -= mn;
        c[i][tata[i]] += mn;
    }

    return 1;
}

void solve()
{
    bellman();

    while(distra());
}

void printFile()
{
    ofstream g("fmcm.out");

    g << rez << "\n";

    g.close();
}

int main()
{
    readFile();

    solve();

    printFile();

    return 0;
}