Cod sursa(job #534981)

Utilizator ssergiussSergiu-Ioan Ungur ssergiuss Data 16 februarie 2011 17:27:18
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 kb
#include <algorithm>
#include <bitset>
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const char Input[] = "fmcm.in";
const char Output[] = "fmcm.out";

const int Dim = 351;
const int Inf = 0x3f3f3f3f;

short int N, M, S, D;
short int t[Dim], cp[Dim][Dim], fl[Dim][Dim];
int XXX;
int c[Dim];
bitset <Dim> f;
vector < pair <short int, short int> > v[Dim];

struct cmp {

    bool operator()( short int x, short int y ) {

        return c[x] > c[y];
    }
};
priority_queue < short int, vector <short int>, cmp > h;

int BellmanFord() {

    short int nod;
    int fm;
    vector < pair <short int, short int> > :: iterator it;

    memset( c, Inf, sizeof( c ) );
    memset( t, 0, sizeof( t ) );
    c[S] = 0;
    h.push( S );
    f[S] = true;

    while( !h.empty() ) {

        nod = h.top();
        h.pop();
        f[nod] = false;

        for( it = v[nod].begin(); it != v[nod].end(); ++it )
            if( cp[nod][it->first] - fl[nod][it->first] > 0 && c[nod] + it->second < c[it->first] ) {

                c[it->first] = c[nod] + it->second;
                t[it->first] = nod;

                if( f[it->first] == false ) {

                    h.push( it->first );
                    f[it->first] = true;
                }
            }
    }

    if( c[D] != Inf ) {

        fm = Inf;
        for( nod = D; t[nod]; nod = t[nod] )
            fm = min( fm, cp[t[nod]][nod] - fl[t[nod]][nod] );
        for( nod = D; t[nod]; nod = t[nod] ) {

            fl[t[nod]][nod] += fm;
            fl[nod][t[nod]] -= fm;
        }
    }
    else
        fm = 0;

    return fm * c[D];

}

int main() {

    ifstream fin( Input );
    ofstream fout( Output );

    short int x, y, z, t;
    int r;

    fin >> N >> M >> S >> D;
    while( M-- ) {

        fin >> x >> y >> z >> t;
        v[x].push_back( make_pair( y, t ) );
        v[y].push_back( make_pair( x, -t ) );
        cp[x][y] = z;
    }

    do {

        r = BellmanFord();
        XXX += r;
    }
    while( r );

    fout << XXX;

    fin.close();
    fout.close();

    return 0;
}