Cod sursa(job #2600673)

Utilizator alex2209alexPavel Alexandru alex2209alex Data 13 aprilie 2020 07:04:16
Problema Flux maxim de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
//----------------------------------------
///Globale
const long long INF = 1000000000,MAX = 351;
long long n,s,dest,cap[MAX][MAX],flux[MAX][MAX],d[MAX],cost[MAX][MAX],par[MAX];
vector<long long>muchii[MAX];
bitset<MAX>ap;
//----------------------------------------
///Functii
void citire();
void rezolvare();
//----------------------------------------
int main()
{
    citire();
    rezolvare();
    return 0;
}
//----------------------------------------
bool bellman()
{
    for(long long i = 1; i <= n; ++i)
        d[i] = INF;
    d[s] = 0;
    queue<long long>q;
    q.push(s);
    ap[s] = 1;
    while(!q.empty())
    {
        long long nod = q.front();
        q.pop();
        ap[nod] = 0;
        for(auto it : muchii[nod])
            if(d[it] > d[nod] + cost[nod][it] && flux[nod][it] < cap[nod][it])
            {
                d[it] = d[nod] + cost[nod][it];
                par[it] = nod;
                if(ap[it] == 0)
                {
                    q.push(it);
                    ap[it] = 1;
                }
            }
    }
    if(d[dest] != INF)
        return 1;
    return 0;
}
//----------------------------------------
void rezolvare()
{
    long long rasp = 0;
    while(bellman())
    {
        long long flow = INF;
        long long nod = dest;
        while(nod != s)
        {
            long long nod2 = par[nod];
            flow = min(flow,cap[nod2][nod] - flux[nod2][nod]);
            nod = nod2;
        }
        nod = dest;
        while(nod != s)
        {
            long long nod2 = par[nod];
            flux[nod2][nod] += flow;
            rasp += flow * cost[nod2][nod];
            nod = nod2;
        }
    }
    g << rasp;
}
//----------------------------------------
void citire()
{
    long long m;
    f >> n >> m >> s >> dest;
    while(m--)
    {
        long long x,y,c,z;
        f >> x >> y >> c >> z;
        cap[x][y] = c;
        cost[x][y] = z;
        cost[y][x] = -z;
        muchii[x].push_back(y);
        muchii[y].push_back(x);
    }
}