Cod sursa(job #1532823)

Utilizator ZenusTudor Costin Razvan Zenus Data 21 noiembrie 2015 17:26:17
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 350 + 10;

int l[nmax] , w[nmax] , v[nmax];
int p[nmax][nmax] , c[nmax][nmax] , f[nmax][nmax];
int a , b , x , y , n , m , s , d , i , t , q0 , w0 , flow;
queue < int > iq;
vector < int > g[nmax];

bool path()
{
    while (iq.size()) iq.pop();

    for (int i = 1 ; i <= n ; ++i)
    w[i] = 0 , v[i] = 0 , l[i] = 1 << 30;

    iq.push(s) , l[s] = 0 , v[s] = 1;

    while (iq.size())
    {
        int q0 = iq.front();
        iq.pop();
        v[q0] = 0;

        for (int i = 0 ; i < g[q0].size() ; ++i)
        {
            int nq = g[q0][i];

            if (l[nq] > l[q0] + p[q0][nq] && c[q0][nq] > f[q0][nq])
            {
                l[nq] = l[q0] + p[q0][nq];
                w[nq] = q0;

                if (v[nq]);
                else v[nq] = 1 , iq.push(nq);
            }
        }
    }

    return w[d];
}

int main()
{
freopen("fmcm.in" , "r" , stdin);
freopen("fmcm.out" , "w" , stdout);

scanf("%d" , &n);
scanf("%d" , &m);
scanf("%d" , &s);
scanf("%d" , &d);

for (i = 1 ; i <= m ; ++i)
{
    scanf("%d" , &a);
    scanf("%d" , &b);
    scanf("%d" , &x);
    scanf("%d" , &y);

    g[a].push_back(b);
    g[b].push_back(a);
    p[a][b] = y;
    c[a][b] = x;
    c[b][a] = -x;
}

while (path())
{
    t = 1 << 30;
    for (q0 = d ; q0 - s ; q0 = w[q0])
    {
        w0 = w[q0];
        t = min(t , c[w0][q0] - f[w0][q0]);
    }

    flow += t * l[d];

    for (q0 = d ; q0 - s ; q0 = w[q0])
    {
        w0 = w[q0];
        f[w0][q0] += t;
        f[q0][w0] -= t;
    }
}

printf("%d\n" , flow);

return 0;
}