Cod sursa(job #2967776)

Utilizator BrioflatorBalescu Alexandru Brioflator Data 20 ianuarie 2023 02:39:58
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

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

int N, M, s, f;
vector<int> tata;
vector<vector<int>> capacitate;
vector<vector<int>> LA;

bool bfs()
{
    vector<bool> viz(N + 1);
    queue<int> q;
    q.push(s);
    viz[s] = true;
    tata[s] = -1;
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        for (auto v : LA[u])
        {
            if (viz[v] == false && capacitate[u][v] != 0)
            {
                tata[v] = u;
                if (v == f)
                    return true;
                viz[v] = true;
                q.push(v);
            }
        }
    }
    return false;
}

int EdmondsKarp()
{
    long max_flow = 0;
    while (bfs())
    {
        int u, v;
        int path_flow = INT_MAX;
        for (v = f; v != s; v = tata[v])
        {
            // gasesc flow ul necesar ca sa nu se creeze bottleneck
            u = tata[v];
            path_flow = min(path_flow, capacitate[u][v]);
        }
        for (v = f; v != s; v = tata[v])
        {
            u = tata[v];
            capacitate[u][v] -= path_flow; // scad flowul gasit din capacitate pe arcele normale
            capacitate[v][u] += path_flow; // adun flow ul gasit pe arcele reverse
        }
        max_flow += path_flow; // adaug flowul gasit la total
    }
    return max_flow;
}

int main()
{
    fin >> N >> M;
    s = 1;
    f = N;
    LA.resize(N + 1);
    tata.resize(N + 1);
    capacitate.resize(N + 1, vector<int>(N + 1));
    for (int i = 1; i <= M; i++)
    {
        int u, v;
        long c;
        fin >> u >> v >> c;
        LA[u].push_back(v);
        LA[v].push_back(u);
        capacitate[u][v] = c;
    }
    fout << EdmondsKarp();
    return 0;
}