Cod sursa(job #2043939)

Utilizator rangal3Tudor Anastasiei rangal3 Data 20 octombrie 2017 19:24:54
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <queue>
#include <vector>
#include <bitset>
#define file "maxflow"
#define N 1003
#define oo 1e7
#define min(a,b) (a < b ? a:b)

using namespace std;

ifstream fin(file".in");
ofstream fout(file".out");

int n,m,x,y,cost;
int c[N][N],f[N][N];

vector<int> g[N];
queue<int> q;

int TT[N];
bitset<N> viz;

inline bool BFS()
{
    int nod,k;
    q.push(1);
    viz.reset();
    viz[1] = 1;

    while(!q.empty())
    {
        nod = q.front();
        q.pop();

        if(nod == n) continue;

        for(int j=0; j!=g[nod].size(); ++j)
        {
            k = g[nod][j];
            if(c[nod][k] - f[nod][k] <=0 || viz[k]) continue;
            TT[k] = nod;
            viz[k] = 1;
            q.push(k);
        }
    }
    return viz[n];
}

void afisare()
{
    fout<<"COST:\n";
    for(int i=1; i<=n; ++i)
    {
        for(int j=1; j<=n; ++j)
            fout<<c[i][j]<<" ";
        fout<<"\n";
    }
}

int main()
{
    fin>>n>>m;
    while(m--)
    {
        fin>>x>>y>>cost;
        c[x][y] += cost;
        //c[y][x] = 0,admite muchie inversa
        g[x].push_back(y);
        g[y].push_back(x);
    }

    int flux,fm = 0;
    int nod;

   // afisare();

    for(flux = 0; BFS();)
    {
        for(int j=0; j!=g[n].size(); ++j)
        {
            nod = g[n][j];
            TT[n] = nod;
            if(!viz[nod] || c[nod][n] - f[nod][n] <=0) continue;

            fm = oo;
            for(nod = n; nod != 1; nod = TT[nod])
                fm = min(fm,c[TT[nod]][nod] - f[TT[nod]][nod]);

            if(fm == 0) continue; //primul drum va fi de ameliorare,
                                 // dar avand muchii comune in arborele nodului 1
                                //  pot aparea muchii prin care nu mai poate trece flux

            for(nod = n; nod != 1; nod = TT[nod])
            {
                f[TT[nod]][nod] += fm;
                f[nod][TT[nod]] -= fm;
            }

            flux += fm;
        }
    }

    fout<<flux<<"\n";

    fin.close(); fout.close();
    return 0;
}