Cod sursa(job #2961714)

Utilizator Eronatedudu zzz Eronate Data 6 ianuarie 2023 21:33:52
Problema Flux maxim Scor 0
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 2.75 kb
#include <bits/stdc++.h>
using namespace std;

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

vector<vector<int>> gr;
vector<vector<int>> flow;

bool bfs(int n, int src, int dest, int father[])
{
    bool visited[n+1];
    memset(visited, 0, sizeof(visited));
    memset(father, 0, sizeof(father));
    queue<int> vertexes;
    vertexes.push(src);

    while(!vertexes.empty())
    {
        int currentNode = vertexes.front();
        vertexes.pop();
        for(auto extr2: gr[currentNode])
        {
            if(extr2!=0)
            if(!visited[extr2] and flow[currentNode][extr2]>0) //daca nu am vizitat nodul extr2
                //si capacitatea muchiei formata din nodul curent si extremitatea 2 permite trecerea flow-ului
            {
                father[extr2] = currentNode;
                if(extr2 == dest)
                    return true;
                vertexes.push(extr2);
                visited[extr2] = true;
            }
        }

    }
    return false; //nu am gasit un drum de la sursa la destinatie, inseamna nu mai am drumuri si ca am ajuns la flux maxim
}

int fordFulkerson(int n, int src, int dest)
{
    int u, v, max_flow_for_route, currentNode;

    int father[n+1];
    memset(father, 0, sizeof(father));
    int srcAux = src, destAux = dest, fNode, finalFlow = 0;

    while(bfs(n, src, dest, father))
    {
        max_flow_for_route = INT_MAX;
        srcAux = src;
        destAux = dest;
        while(destAux!=srcAux)
        {
            //calculez flow-ul maxim de transmis pe drumul gasit de bfs
            max_flow_for_route = min(max_flow_for_route, flow[father[destAux]][destAux]);
            destAux = father[destAux];
        }
        destAux = dest;
        srcAux = src;
        //acum updatez graful rezidual pe drumul gasit de bfs
        while(destAux!=srcAux)
        {
            fNode = father[destAux];
            flow[fNode][destAux] -= max_flow_for_route;    //muchia mea pe directia corecta va avea o capacitate mai mica de flow
            flow[destAux][fNode] += max_flow_for_route;    //muchia pe directia inversa va avea mai mult flow de dat
            //logic pt ca voi avea mai mult flow de extras
            destAux = fNode;
        }

        finalFlow += max_flow_for_route; //adun flow-ul drumului la flow-ul final
    }
    return finalFlow;
}
int main()
{

    int n,m,node1,node2,flux;
    f>>n>>m;
    flow.resize(1001);
    gr.resize(1001);
    for(int i=1;i<=1001;i++)
        flow[i].resize(1001);
    for(int i=1;i<=m;i++)
    {
        f>>node1>>node2>>flux;
        gr[node1].push_back(node2);
        gr[node2].push_back(node1);
        flow[node1][node2] = flux;
    }

    g<<fordFulkerson(n,1,n);
    return 0;
}