Cod sursa(job #2960016)

Utilizator cilteaioanaIoana C cilteaioana Data 3 ianuarie 2023 14:03:37
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

vector<vector<int>> la, grafRez;
vector<int> tata;
queue<int> q;

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

int BFS()
{
    int n = la.size() - 1;
    vector<bool> viz(n + 1, false);
    int maxFlow = 0;
    q.push(1);
    viz[1] = true;

    while (!q.empty()) 
    {
        int nCurent = q.front();
        q.pop();
        for (auto vecin : la[nCurent])
        {
            if (!viz[vecin] && vecin != n && grafRez[nCurent][vecin] > 0)
            {
                viz[vecin] = true;
                q.push(vecin);
                tata[vecin] = nCurent;
            }
        }
    }

    for (auto vecin : la[n]) 
    {
        if (!viz[vecin])
            continue;

        int F = grafRez[vecin][n];
        int nCurent = vecin;

        while (nCurent != 1)
        {
            F = min(F, grafRez[tata[nCurent]][nCurent]);
            nCurent = tata[nCurent];
        }

        grafRez[vecin][n] -= F;
        grafRez[n][vecin] += F;

        nCurent = vecin;
        while (current != 1) 
        {
            current = tata[nCurent];
            grafRez[tata[nCurent]][nCurent] -= F;
            grafRez[nCurent][tata[nCurent]] += F;
        }
        maxFlow += F;
    }

    return maxFlow;
}

int getMaxFlow()
{
    int n = la.size() - 1;

    tata.resize(n + 1, -1);

    int totalMaxFlow = 0;
    
    int pathFlow = BFS(); //primul augmenting path
    
    while (pathFlow)
    {
        totalMaxFlow += pathFlow;
        pathFlow = BFS();
    }

    return totalMaxFlow;
}

int main() 
{
    int n, m;
    fin >> n >> m;

    la.resize(n + 1);
    grafRez.resize(n + 1, vector<int>(n + 1, 0));

    for (int i = 0; i < m; i++) 
    {
        int x, y, z;
        fin >> x >> y >> z;
        la[x].push_back(y);
        la[y].push_back(x);
        grafRez[x][y] += z;
    }

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