Cod sursa(job #2962585)

Utilizator AntoniaPopoviciAntonia-Adelina Popovici AntoniaPopovici Data 8 ianuarie 2023 19:12:57
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <queue>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define MAXN 360
#define INF 0x3f3f3f3f

using namespace std;

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

typedef pair< int, int > pereche;
int N, s, t;
int d[MAXN], f[MAXN];
int C[MAXN][MAXN], D[MAXN][MAXN];
vector< int > v;
vector< int > graf[MAXN];
vector< int >:: iterator it, it2;
struct cmp
{
     bool operator() (const int& x, const int& y) const
    {
        return d[x] > d[y];
    }
};

 bool find_path(void)
{
    int x;
    vector< bool > inH(N + 1);
    priority_queue< int, vector< int >, cmp > prq;
    fill(d + 1, d + N + 1, INF);
    f[s] = 0;
    d[s] = 0;
    for (prq.push(s); !prq.empty(); )
    {
        x = prq.top(); prq.pop();
        inH[x] = false;
        for (it = graf[x].begin(), it2 = graf[x].end(); it < it2; ++it)
        {
            if (s == *it)
                continue;
            if (C[x][*it] > 0 && d[x] + D[x][*it] < d[*it])
            {
                f[*it] = x;
                d[*it] = d[x] + D[x][*it];
                if (false == inH[*it])
                {
                    prq.push(*it);
                    inH[*it] = true;
                }
            }
        }
    }
    return INF != d[t];
}
int main(void)
{
    int M, x, y, c;
    for (fin >> N >> M >> s >> t; M; --M)
    {
        fin >> x >> y;
        fin >> C[x][y] >> D[x][y];
        D[y][x] = -D[x][y];
        graf[x].push_back(y);
        graf[y].push_back(x);
        if (t == x)
            v.push_back(y);
        else if (t == y)
            v.push_back(x);
    }
    for (x = 0; find_path(); )
    {
        for (it = v.begin(), it2 = v.end(); it < it2; ++it)
        {
            M = *it;
            if (d[t] == d[M] + D[M][t] && C[M][t] > 0)
            {
                c = C[M][t];
                for (y = M; f[y]; y = f[y])
                    if (c > C[f[y]][y])
                        c = C[f[y]][y];
                C[M][t] -= c;
                C[t][M] += c;
                for (y = M; f[y]; y = f[y])
                {
                    C[f[y]][y] -= c;
                    C[y][f[y]] += c;
                }
                x += c * d[t];
            }
        }
    }
    fout << x << '\n';
    return 0;
}