Cod sursa(job #2550018)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 18 februarie 2020 11:16:49
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 1000;

int N, M, S, D;
int c[NMAX + 2][NMAX + 2], f[NMAX + 2][NMAX + 2];

vector <int> g[NMAX + 5];

int bef[NMAX + 5];
bool seen[NMAX + 5];

bool BFS()
{
    queue <int> Q;

    for(int i = 1; i <= N; i++)
        seen[i] = 0;

    Q.push(S);
    seen[S] = 1;

    while(!Q.empty())
    {
        int node = Q.front();
        Q.pop();

        for(auto it : g[node])
            if(!seen[it] && f[node][it] < c[node][it])
            {
                seen[it] = 1;
                bef[it] = node;
                Q.push(it);
            }
    }

    return seen[D];
}

int main()
{
    fin >> N >> M;

    for(int i = 1; i <= M; i++)
    {
        int x, y, cap;
        fin >> x >> y >> cap;

        c[x][y] = cap;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    S = 1, D = N;

    while(BFS())
    {
        for(auto it : g[D])
        {
            int flow = c[it][D] - f[it][D];

            for(int node = it; node != S; node = bef[node])
                flow = min(flow, c[bef[node]][node] - f[bef[node]][node]);

            f[it][D] += flow;
            f[D][it] -= flow;

            for(int node = it; node != S; node = bef[node])
            {
                f[bef[node]][node] += flow;
                f[node][bef[node]] -= flow;
            }
        }
    }

    int maxFlow = 0;
    for(auto it : g[S])
        maxFlow += f[S][it];

    fout << maxFlow << '\n';

    return 0;
}