Cod sursa(job #717366)

Utilizator vendettaSalajan Razvan vendetta Data 19 martie 2012 21:14:33
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <vector>
#include <queue>
#define nmax 355

using namespace std;

ifstream f("fmcm.in");
ofstream g("fmcm.out");

int n, m, s, dest, cost[nmax][nmax], capacitate[nmax][nmax], flux[nmax][nmax];
int viz[nmax], T[nmax], d[nmax], Rez;
queue<int> q;
vector<int> gf[nmax];

void citeste(){

    f >> n >> m >> s >> dest;

    for(int i=1; i<=m; i++){
        int x, y, capac, pret;
        f >> x >> y >> capac >> pret;
        gf[x].push_back(y);
        gf[y].push_back(x);
        cost[x][y] = pret;
        cost[y][x] = -pret;
        capacitate[x][y] = capac;
    }

}

int bf(){

    for(int i=0; i<=n+1; i++) d[i] = (1<<30), viz[i] = 0, T[i] = 0;
    d[s] = 0;
    viz[s] = 1;
    for(; q.size(); q.pop());
    q.push(s);

    for(; q.size(); ){
        int nod = q.front();
        q.pop();
        viz[nod] = 0;
        for(int i=0; i<gf[nod].size(); i++){
            int vc = gf[nod][i];
            if (capacitate[nod][vc] > flux[nod][vc] && d[vc] > d[nod] + cost[nod][vc]){
                d[vc] = d[nod] + cost[nod][vc];
                T[vc] = nod;
                if (viz[vc] == 0){
                    viz[vc] = 1;
                    q.push(vc);
                }
            }
        }
    }

    if (d[dest] != (1<<30) ){
        return 1;
    }

   return 0;

}

void rezolva(){

    for(; bf(); ){
        int Min = (1<<29);
        for(int i=dest; i!=s; i=T[i])
            //am muchia t[i]->i
            Min = min(Min, capacitate[T[i]][i] - flux[T[i]][i]);

        for(int i=dest; i!=s; i=T[i]){
            //pe muchi t[i]->i adaug flux pe i->t[i](inversa) il scad
            flux[T[i]][i] += Min;
            flux[i][T[i]] -= Min;
        }
        Rez += d[dest] * Min;
    }

}

void scrie(){

    g << Rez << "\n";

}

int main(){

    citeste();
    rezolva();
    scrie();

    f.close();
    g.close();

    return 0;

}