Cod sursa(job #850864)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 9 ianuarie 2013 00:49:10
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.57 kb
#include <fstream>
#include <queue>
#include <vector>
 
using namespace std;
 
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
 
const int inf= 1<<30;
const int nmax= 350; 
 
struct str{
    int x, y;
    str(int _x, int _y){
        x= _x; y= _y;
    };
};
 
int n;
vector <int> g[nmax+1];
int cpc[nmax+1][nmax+1], cst[nmax+1][nmax+1];
 
bool uq[nmax+1];
int old_d[nmax+1];
queue <int> q;
 
struct cmp_str{
    bool operator()(str a, str b){
        return a.y>b.y;
    }
};
 
int d[nmax+1], new_d[nmax+1], p[nmax+1];
priority_queue <str, vector <str>, cmp_str> h;
 
bool dijkstra(int src, int dest){
    for (int i= 1; i<=n; ++i){
        d[i]= inf;
    }
    d[src]= 0; new_d[src]= 0; 
    h.push(str(src, 0));
    while (!h.empty()){
        int x= h.top().x, y= h.top().y;
        h.pop();
        if (d[x]==y){
            for (vector <int>::iterator it= g[x].begin(); it!=g[x].end(); ++it){
                if (cpc[x][*it]>0){
                    int aux= y+cst[x][*it]+old_d[x]-old_d[*it];
                    if (aux<d[*it]){
                        d[*it]= aux; 
                        new_d[*it]= new_d[x]+cst[x][*it];
                        p[*it]= x;
                        h.push(str(*it, aux));
                    }
                }
            }
        }
    }
    for (int i= 1; i<=n; ++i){
        old_d[i]= new_d[i];
    }
    if (d[dest]==inf){
        return 0;
    }else{
        return 1;
    }
}
 
int main(){
    int m, src, dest;
    fin>>n>>m>>src>>dest;
    for (int i= 1; i<=m; ++i){
        int x, y;
        fin>>x>>y;
        g[x].push_back(y); g[y].push_back(x);
        fin>>cpc[x][y]>>cst[x][y];
        cst[y][x]= -cst[x][y];
    }
 
    for (int i= 1; i<=n; ++i){
        old_d[i]= inf;
    }
    old_d[src]= 0;
    q.push(src); uq[src]= 1;
     
    while (!q.empty()){
        int x= q.front();
        q.pop(); uq[x]= 0;
         
        for (vector <int>::iterator it= g[x].begin(); it!=g[x].end(); ++it){
            if (cpc[x][*it]>0&& old_d[*it]>old_d[x]+cst[x][*it]){
                old_d[*it]= old_d[x]+cst[x][*it];
                if (!uq[*it]){
                    q.push(*it); uq[*it]= 1;
                }
            }
        }
    }

    int fm= 0, cm= 0;
    while (dijkstra(src, dest)){
        int aux= inf;
        for (int i= dest; i!=src; i= p[i]){
            if (aux>cpc[p[i]][i]){
                aux= cpc[p[i]][i];
            }
        }
        fm+= aux;
        for (int i= dest; i!=src; i= p[i]){
            cm+= cst[p[i]][i]*aux;
            cpc[p[i]][i]-= aux;
            cpc[i][p[i]]+= aux;
        }
    }
    fout<<cm<<"\n";

    return 0;
}