Cod sursa(job #1516277)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 2 noiembrie 2015 21:51:07
Problema Flux maxim de cost minim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <limits.h>

#define DIM 351
#define INF INT_MAX

using namespace std;

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

int N, M, beginning, ending, x, y, cap, c, minimum, solution;
int capacity[DIM][DIM], flow[DIM][DIM], cost[DIM][DIM];
int T[DIM], D[DIM], q[20 * DIM];

vector<int>L[DIM];
bitset<DIM>V;

int bellman_ford()
{
    for(int i = 1; i <= N; i ++)
    {
        D[i] = INF;
        V[i] = 0;
    }

    int p = 1, u = 1;
    q[1] = beginning;

    while(p <= u)
    {
        V[ q[p] ] = 1;

        for(int i = 0; i < L[ q[p] ].size(); i ++)
        {
            int neighbour = L[ q[p] ][i];

            if( (D[neighbour] > D[ q[p] ] + cost[ q[p] ][neighbour]) && (flow[ q[p] ][neighbour] < capacity[ q[p] ][neighbour] ) )
            {
                D[neighbour] = D[ q[p] ] + cost[ q[p] ][neighbour];
                T[ neighbour ] = q[p];

                if(V[neighbour] == 0)
                {
                    q[++ u] = neighbour;
                    V[neighbour] = 1;
                }
            }
        }
        V[ q[p] ] = 0;
        p ++;
    }

    if(D[ending] != INF)
    {
        return 1;
    }

    return 0;
}


int main()
{
    fin >> N >> M >> beginning >> ending;

    for(int i = 1; i <= M; i ++)
    {
        fin >> x >> y >> cap >> c;
        L[x].push_back(y);
        L[y].push_back(x);

        capacity[x][y] = cap;
        cost[x][y] = c;
        cost[y][x] = -c;
    }

    while(bellman_ford())
    {
        minimum = INF;
        int x = ending;

        while(x != beginning)
        {
            if(minimum > capacity[ T[x] ][x] - flow[ T[x] ][x]  )
            {
                minimum = capacity[ T[x] ][x] - flow[ T[x] ][x];
            }

            x = T[x];
        }

        x = ending;

        while(x != beginning)
        {
            solution += minimum * cost[ T[x] ][x];
            flow[ T[x] ][x] += minimum;
            flow[x][ T[x] ] -= minimum;

            x = T[x];
        }
    }

    fout << solution;

    return 0;
}