Cod sursa(job #689447)

Utilizator cdascaluDascalu Cristian cdascalu Data 24 februarie 2012 15:13:12
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include<fstream>
#include<queue>
#include<vector>
#include<bitset>
#define Nmax 351
#define INF 0x3f3f3f
using namespace std;

int N,M,S,D;

short int C[Nmax][Nmax],F[Nmax][Nmax],t[Nmax];

int d[Nmax];

vector< pair<short int,short int> >G[Nmax];

void read()
{
    ifstream f("fmcm.in");

    f>>N>>M>>S>>D;

    int i,x,y,z,c;

    for(i=1;i<=M;++i)
    {
        f>>x>>y>>c>>z;
        C[x][y] = c;
        G[x].push_back( make_pair(y,z) );
        G[y].push_back( make_pair(x,-z) );
    }

    f.close();
}
int bellman(int S,int D)
{
    fill(d+1,d+N+1,INF);
    fill(t+1,t+N+1,0);

    bitset<Nmax> in;

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

    in.reset();
    Q.push(S);
    in[S]       = true;
    d[S]        = 0;
    t[S]        = S;
    while(!Q.empty())
    {
        nod = Q.front();
        Q.pop();

        in[nod] = false;
        if(nod == D)continue;

        for(it = G[nod].begin();it!=G[nod].end();++it)
            if(d[it->first] > d[nod] + it->second && C[nod][it->first] > F[nod][it->first])
            {
                d[it->first] = d[nod] + it->second;
                t[it->first] = nod;
                if(in[it->first] == false)
                {
                    Q.push(it->first);
                    in[it->first] = true;
                }
            }
    }

    return t[D];
}
short int minim(short int a,short int b)
{
    if(a<=b)
        return a;
    return b;
}
int main()
{
    read();

    int r,cost=0,i;

    while(bellman(S,D))
    {
        r       = INF;
        i       = D;
        while(i != S)
        {
            r = minim(r,C[ t[i] ][i] - F[ t[i] ][i]);
            i = t[i];
        }
        if(r==0)continue;

        i       = D;
        while(i!=S)
        {
            F[ t[i] ][i] += r;
            F[i][ t[i] ] -= r;
            i = t[i];
        }
        cost += r*d[D];
    }
    ofstream g("fmcm.out");
    g<<cost<<"\n";
    g.close();
    return 0;
}