Cod sursa(job #933724)

Utilizator visanrVisan Radu visanr Data 30 martie 2013 12:04:26
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;

#define Nmax 360
#define pb push_back
#define forit(it, v) for(typeof((v).begin()) it = (v).begin(); it != (v).end(); ++ it)
#define Inf 0x3f3f3f3f

int N, M, X, Y, C, Z, Source, Sink, Cost[Nmax][Nmax], Flow[Nmax][Nmax], Cap[Nmax][Nmax], Father[Nmax];
int Dist[Nmax];
bool InQueue[Nmax];
vector<int> G[Nmax];

bool BellmanFord()
{
    for(int i = 1; i <= N; ++ i)
    {
        Dist[i] = Inf;
        Father[i] = 0;
        InQueue[i] = 0;
    }
    queue<int> Q;
    Q.push(Source);
    InQueue[Source] = 1;
    Dist[Source] = 0;
    while(!Q.empty())
    {
        int Node = Q.front();
        Q.pop();
        InQueue[Node] = 0;
        forit(it, G[Node])
            if(Cap[Node][*it] > Flow[Node][*it] && Dist[*it] > Dist[Node] + Cost[Node][*it])
            {
                Dist[*it] = Dist[Node] + Cost[Node][*it];
                Father[*it] = Node;
                if(!InQueue[*it])
                {
                    InQueue[*it] = 1;
                    Q.push(*it);
                }
            }
    }
    return (Dist[Sink] != Inf);
}

int MinCostMaxFlow()
{
    int Ans = 0;
    while(BellmanFord())
    {
        int MinFlow = Inf;
        for(int Node = Sink; Node != Source; Node = Father[Node])
            MinFlow = min(MinFlow, Cap[Father[Node]][Node] - Flow[Father[Node]][Node]);
        for(int Node = Sink; Node != Source; Node = Father[Node])
        {
            Flow[Father[Node]][Node] += MinFlow;
            Flow[Node][Father[Node]] -= MinFlow;
        }
        Ans += MinFlow * Dist[Sink];
    }
    return Ans;
}

int main()
{
    freopen("fmcm.in", "r", stdin);
    freopen("fmcm.out", "w", stdout);
    int i, j;
    scanf("%i %i %i %i", &N, &M, &Source, &Sink);
    for(i = 1; i <= M; ++ i)
    {
        scanf("%i %i %i %i", &X, &Y, &C, &Z);
        G[X].pb(Y);
        G[Y].pb(X);
        Cap[X][Y] = C;
        Cost[X][Y] = Z;
        Cost[Y][X] = -Z;
    }
    printf("%i\n", MinCostMaxFlow());
    return 0;
}