Cod sursa(job #968651)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 2 iulie 2013 14:43:46
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <bitset>
#include <queue>

#define In "maxflow.in"
#define Out "maxflow.out"
#define min(a,b) ((a)<(b)?(a):(b))

#define Nmax 1002
#define source 1
#define destination N
#define Inf 0x3f3f3f3f
#define pb push_back

using namespace std;

int N, F[Nmax][Nmax], C[Nmax][Nmax] , Father[Nmax], MaxFlow;
vector<short>Graph[Nmax];
bitset<Nmax>viz;
queue<short>Q;

inline void Read()
{
    ifstream f(In);
    int M, X, Y, Z;
    f>> N >> M;
    while(M--)
    {
        f >> X >> Y >> Z;
        C[X][Y]  = Z;
        Graph[X].pb(Y);
    }
    f.close();
}

inline bool Bfs()
{
    Q.push(source);
    int _node;
    for(_node = 1; _node <= N; ++_node)
        viz[_node] = 0;
    viz[source] = 1;
    vector<short> :: iterator it;
    while(!Q.empty())
    {
        _node = Q.front();
        Q.pop();
        if(_node==destination)
            continue ;
        for(it = Graph[_node].begin();it!=Graph[_node].end();++it)
            if(!viz[*it]&& F[_node][*it]<C[_node][*it])
            {
                viz[*it] = 1;
                Q.push(*it);
                Father[*it]  = _node;
            }
    }
    return viz[destination];
}

inline void Solve()
{
    vector<short> :: iterator it;
    int _node, _min, i;
    while(Bfs())
    {
        for(i = 1;i < N; ++i)
        {
            if(!C[i][destination] || !viz[i] || C[i][destination]==F[i][destination])
                continue;
            Father[destination] = i;
            for(_node = destination,_min = Inf;_node!=source; _node = Father[_node])
                _min = min(_min,C[Father[_node]][_node]-F[Father[_node]][_node]);
            for(_node = destination;_node!=source; _node = Father[_node])
                F[Father[_node]][_node] += _min;
            MaxFlow += _min;
        }
    }
}

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

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