Cod sursa(job #2272854)

Utilizator CriogeniXBociat Daniel Tiberiu CriogeniX Data 30 octombrie 2018 18:53:52
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMax = 1000;
const int oo = 111000;
vector <int> G[NMax + 5];
queue <int> Q;
int C[NMax + 5][NMax],F[NMax + 5][NMax + 5];
int TT[NMax + 5], Use[NMax + 5];
int N,M,MaxFlow;
void Read()
{
    fin >> N >> M;
    for(int i = 1; i <= M; ++i)
    {
        int x,y,c;
        fin >> x >> y >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] += c;
        C[y][x] = 0;
    }
}

void Init()
{
    while(!Q.empty())
        Q.pop();
    memset(Use,0, sizeof(Use));
    memset(TT,0, sizeof(TT));
}

int BFS()
{
    Init();
    Q.push(1);
    Use[1] = 1;
    while(!Q.empty() && !Use[N])
    {
        int Nod = Q.front(); Q. pop();
        for(int i = 0; i < (int)G[Nod].size(); ++i)
        {
            int Vecin = G[Nod][i];
            if(C[Nod][Vecin] - F[Nod][Vecin] == 0) continue;
            if(Use[Vecin] == 0)
            {
                TT[Vecin] = Nod;
                Use[Vecin] = 1;
                Q.push(Vecin);
                if(Vecin == N) return 1;
            }
        }
    }
    return 0;
}
void Print()
{
    fout << MaxFlow << "\n";
}

int main()
{
    Read();

    while(BFS())
    {
        int Flow = oo;
        for(int Nod = N; Nod != 1; Nod = TT[Nod])
        {
            int Tata = TT[Nod];
            Flow = min(Flow,C[Tata][Nod]-F[Tata][Nod]);
        }
        for(int Nod = N; Nod != 1; Nod = TT[Nod])
        {
            int Tata = TT[Nod];
            F[Tata][Nod] += Flow;
            F[Nod][Tata] -= Flow;
        }
        MaxFlow += Flow;
    }

    Print();
    return 0;
}