Cod sursa(job #1332521)

Utilizator ThomasFMI Suditu Thomas Thomas Data 2 februarie 2015 09:40:15
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

#define NMax 1005
#define inf 2100000000

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int n,m;
vector<int> v[NMax];
queue<int> cd;

int C[NMax][NMax];
int F[NMax][NMax];
bool viz[NMax];
int ant[NMax];

bool BFS(int s)
{
    int i;

    for(i=1;i<=n;++i) viz[i] = false;
    viz[s] = true;
    cd.push(s);

    while(!cd.empty())
    {
        s = cd.front(); cd.pop();
        if(s!=n) for(i=0;i<v[s].size();++i) if(!viz[v[s][i]] && F[s][v[s][i]] < C[s][v[s][i]])
        {
            ant[v[s][i]] = s;
            viz[v[s][i]] = true;
            cd.push(v[s][i]);
        }
    }

    return viz[n];
}

int main()
{
    int i,a,b,c;

    f>>n>>m;
    while(m--)
    {
        f>>a>>b>>c;
        v[a].push_back(b);
        v[b].push_back(a);
        C[a][b] += c;
    }

    int flow = 0, newflow, s;

    while(BFS(1)) for(i=0;i<v[n].size();++i)
    {
        ant[n] = v[n][i];
        newflow = inf;
        s = n;
        while(s != 1)
        {
            newflow = min( newflow , C[ant[s]][s] - F[ant[s]][s] );
            s = ant[s];
        }

        s = n;
        while(s != 1)
        {
            F[ant[s]][s] += newflow;
            F[s][ant[s]] -= newflow;
            s = ant[s];
        }
        flow += newflow;
    }

    g<<flow<<"\n";

    f.close();
    g.close();
    return 0;
}