Cod sursa(job #751388)

Utilizator BitOneSAlexandru BitOne Data 25 mai 2012 22:04:00
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <queue>
#include <vector>
#include <fstream>
#include <cstdlib>


using namespace std;
typedef pair<int, int> pr;

const int N_MAX=411;
const int oo=536870912;


vector<pr> G[N_MAX];
vector<pr>::const_iterator it, iend;
bool was[N_MAX];
int F[N_MAX][N_MAX], C[N_MAX][N_MAX], d[N_MAX], f[N_MAX];
class cmp {
public : bool operator() (const int& x, const int& y) {return d[x] > d[y];}
};
priority_queue<int, vector<int>, cmp> pQ;


bool BellmanFord(int source, int sink, int N)
{
    int x;

    for(x=1; x <= N; ++x)
    {
        f[x]=-1;
        d[x]=oo;
        was[x]=false;
    }
    f[source]=-2;
    d[source]=0;
    for(pQ.push(source); !pQ.empty(); )
    {
        x=pQ.top(); pQ.pop();
        was[x]=false;
        for(it=G[x].begin(), iend=G[x].end(); it < iend; ++it)
        {
            if(source == it->first)
                continue;
            if(d[it->first] > it->second + d[x] && C[x][it->first] > F[x][it->first])
            {
                d[it->first]=it->second+d[x];
                f[it->first]=x;
                if(false == was[it->first])
                {
                    pQ.push(it->first);
                    was[it->first]=true;
                }
            }
        }
    }
    return oo != d[sink] && -1 != f[sink];
}
inline int _min(int x, int y) {return x <= y ? x : y;}
int main()
{
    int N, M, source, sink, x, y, c, cost, cMin;
    long long int s;
    ifstream in("fmcm.in");
    ofstream out("fmcm.out");

    for(in>>N>>M>>source>>sink; M; --M)
    {
        in>>x>>y>>c>>cost;
        G[x].push_back(pr(y, cost));
        G[y].push_back(pr(x, -cost));
        C[x][y]=c;
    }
    s=0;
    while(BellmanFord(source, sink, N))
    {
        cMin=oo;
        for(x=sink; -2 != f[x]; x=f[x])
            cMin=_min(cMin, C[f[x]][x] - F[f[x]][x]);
        for(x=sink; -2 != f[x]; x=f[x])
        {
            F[x][f[x]]-=cMin;
            F[f[x]][x]+=cMin;
        }
        s+=1LL*cMin*d[sink];
    }
    out<<s<<"\n";
    return EXIT_SUCCESS;
}