Cod sursa(job #1340758)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 12 februarie 2015 00:24:57
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <cstring>

#define In "fmcm.in"
#define Out "fmcm.out"
#define Nmax 351
#define Inf 0x3f3f3f3f
#define PII pair<int,int>
using namespace std;
int source, destination, N, Sol;
int od[Nmax], Father[Nmax], cost[Nmax][Nmax], C[Nmax][Nmax];
bitset<Nmax>in_queue;
vector<int>Graph[Nmax];
inline void Read()
{
    int X, Y, c, f, M;
    ifstream fin(In);
    fin>> N >> M >> source >> destination;
    while(M--)
    {
        fin>> X >> Y >> f >> c;
        Graph[X].push_back(Y);
        Graph[Y].push_back(X);
        C[X][Y] = f;
        cost[X][Y] = c;
        cost[Y][X] = -c;
    }
    fin.close();
}

inline bool Bellman_Ford()
{
    queue<int>Q;
    Q.push(source);
    in_queue = 0;
    in_queue[source] = true;
    memset(od,Inf,sizeof(od));
    od[source] = 0;
    int curent;
    vector<int>::iterator it;
    while(!Q.empty())
    {
        curent = Q.front();
        Q.pop();
        in_queue[curent] = false;
        for(it=Graph[curent].begin();it!=Graph[curent].end();++it)
            if(C[curent][*it] && od[*it]>od[curent]+cost[curent][*it])
            {
                od[*it] = od[curent] + cost[curent][*it];
                Father[*it] = curent;
                if(in_queue[*it] == false)
                {
                    in_queue[*it] = true;
                    Q.push(*it);
                }
            }
    }
    return (od[destination]!=Inf);
}

inline void Solve()
{
    int t, _min;
    while(Bellman_Ford())
    {
       for(_min = Inf,t = destination;t != source;t = Father[t])
            _min = min(_min,C[Father[t]][t]);
        Sol += _min*od[destination];
        for(t = destination;t != source;t = Father[t])
        {
            C[Father[t]][t] -= _min;
            C[t][Father[t]] += _min;
        }
    }
}


inline void Write()
{
    ofstream g(Out);
    g<<Sol<<"\n";
    g.close();
}

int main()
{
    Read();
    Bellman_Ford();
    Solve();
    Write();
    return 0;
}