Cod sursa(job #3187881)

Utilizator superffffalexandru radu superffff Data 30 decembrie 2023 22:39:26
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
/*
 * C++ Program to Implement The Edmonds-Karp Algorithm
 */
#include<cstdio>
#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
#include<iostream>
#include<conio.h>
#include<fstream>

using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int capacities[1005][1005];
int flowPassed[1005][1005];
vector<int> graph[1005];
int parentsList[1005];
int currentPathCapacity[1005];

int bfs(int startNode, int endNode)
{
    memset(parentsList, -1, sizeof(parentsList));
    memset(currentPathCapacity, 0, sizeof(currentPathCapacity));

    queue<int> q;
    q.push(startNode);

    parentsList[startNode] = -2;
    currentPathCapacity[startNode] = 999;

    while(!q.empty())
    {
        int currentNode = q.front();
        q.pop();

        for(int i=0; i<graph[currentNode].size(); i++)
        {
            int to = graph[currentNode][i];
            if(parentsList[to] == -1)
            {
                if(capacities[currentNode][to] - flowPassed[currentNode][to] > 0)
                {
                    parentsList[to] = currentNode;
                    currentPathCapacity[to] = min(currentPathCapacity[currentNode],
                    capacities[currentNode][to] - flowPassed[currentNode][to]);
                    if(to == endNode)
                    {
                        return currentPathCapacity[endNode];
                    }
                    q.push(to);
                }
            }
        }
    }
    return 0;
}

int edmondsKarp(int startNode, int endNode)
{
    int maxFlow = 0;
      while(true)
    {
        int flow = bfs(startNode, endNode);
        if (flow == 0)
        {
            break;
        }
        maxFlow += flow;
        int currentNode = endNode;
        while(currentNode != startNode)
        {
            int previousNode = parentsList[currentNode];
            flowPassed[previousNode][currentNode] += flow;
            flowPassed[currentNode][previousNode] -= flow;
            currentNode = previousNode;
        }
    }
    return maxFlow;
}
int main()
{
    int nodesCount, edgesCount;
    in>>nodesCount>>edgesCount;

    int source, sink;
    source=1;
    sink=nodesCount;

    for(int edge = 0; edge < edgesCount; edge++)
    {
        int from, to, capacity;
        in>>from>>to>>capacity;

        capacities[from][to] = capacity;
        graph[from].push_back(to);

        graph[to].push_back(from);
    }

    int maxFlow = edmondsKarp(source, sink);

    out<<maxFlow;

    getch();
}