Minimum Cost to Reverse Edges such that there is Path Between Every Pair of Nodes


The minimum cost to invert edges in order to have a way between each match of hubs alludes to finding the slightest costly way to alter the course of edges in a chart. The objective is to guarantee that there's a way to interconnect any two hubs within the chart. This may involve changing the course of a few edges to set up the network. The least taken toll speaks to the smallest cumulative weight related to reversing the edges. By minimising the fetch, we are able to accomplish the specified result of having a way between all sets of hubs, while optimising the generally included cost in adjusting the chart.

Methods Used

  • Greedy Algorithm

  • Floyd−Warshall Algorithm with Edge Reversal Cost

Greedy Algorithm

The minimum cost to switch edges in order to set up a way between each combination of nodes can be accomplished employing an Eager calculation. In this approach, we begin with a self−assertive hub and iteratively select the edge with the least toll to invert among all the edges that interface to an unvisited hub. By rehashing this preparation until all hubs have been gone to, we guarantee that a way is made between each match of hubs. This calculation depends on the rule of making locally ideal choices at each step, coming about in a universally ideal arrangement in terms of minimising the generally taken toll of edge inversion.

Algorithm

  • Initialise a purge set called "gone by" to keep track of gone−to nodes.

  • Select a self−assertive beginning hub and include it in the "gone to" set.

  • Create a purge−need line called "pq" to store the edges.

  • For each active edge from the beginning node:

  • Add the edge to pq," with taking a toll as the priority.

  • Initialise a variable "fetched" to 0, speaking to the whole toll of edge reversal.

  • While the "gone by" set does not contain all nodes:

  • Extract the edge with the least toll from "pq".

  • If the destination node of the edge isn't within the "gone by" set,

  • Add the goal hub to the "gone to" set.

  • Add the fetch of the edge to the "taken a toll" variable.

  • For each active edge from the goal node:

  • Add the edge to "pq" with its fetched as the priority.

  • Output the ultimate "fetched" variable, which speaks to the least fetched to turn around edges.

Example

#include <iostream>
#include <vector>
#include <climits>

int getMinCost(const std::vector<std::pair<std::pair<int, int>, int>>& edges, int numVertices) {
    std::vector<std::vector<int>> graph(numVertices, std::vector<int>(numVertices, INT_MAX));

    for (const auto& edge : edges) {
        int u = edge.first.first - 1;
        int v = edge.first.second - 1;
        int cost = edge.second;

        graph[u][v] = cost;
    }

    for (int k = 0; k < numVertices; k++) {
        for (int i = 0; i < numVertices; i++) {
            for (int j = 0; j < numVertices; j++) {
                if (graph[i][k] != INT_MAX && graph[k][j] != INT_MAX) {
                    graph[i][j] = std::min(graph[i][j], graph[i][k] + graph[k][j]);
                }
            }
        }
    }

    int minCost = INT_MAX;
    for (int i = 0; i < numVertices; i++) {
        for (int j = 0; j < numVertices; j++) {
            if (i != j) {
                minCost = std::min(minCost, graph[i][j] + graph[j][i]);
            }
        }
    }

    return minCost;
}

int main() {
    int numVertices = 5;
    std::vector<std::pair<std::pair<int, int>, int>> edges = {
        { { 1, 2 }, 7 },
        { { 5, 1 }, 8 },
        { { 5, 4 }, 5 },
        { { 3, 4 }, 1 },
        { { 3, 2 }, 10 }
    };

    int minCost = getMinCost(edges, numVertices);
    if (minCost == INT_MAX) {
        std::cout << "No minimum cost found.\n";
    } else {
        std::cout << "Minimum cost: " << minCost << '\n';
    }

    return 0;
}

Output

Minimum cost: -2147483648

Floyd−Warshall Algorithm with Edge Reversal Cost

The Floyd−Warshall algorithm with edge inversion taking a toll could be an energetic programming calculation utilised to discover the most brief ways between all sets of hubs in a weighted chart. It expands the classic Floyd−Warshall calculation by considering the fetch of turning around edges. The calculation keeps up a separate framework that speaks to the most brief separations between each combination of hubs. By iteratively considering each hub as a halfway vertex, it checks in the event that the way through the middle of the road hub produces a shorter remove. Also, it considers the fetchedness of switching edges to discover the least fetchedness of coming to each hub. This calculation guarantees that the most limited ways are calculated, whereas bookkeeping for the fetch of edge inversion

Algorithm

  • Make a remove framework dist of measure N x N, initialised with limitlessness for all sets of hubs, where N is the number of hubs within the graph.

  • Initialise dist [i] [j] with the weight of the edge between hubs i and j for all existing edges.

  • For each hub, i:

  • Set dist[i][i] to 0, speaking to separate from a hub to itself.

  • For each hub k from 1 to N:

  • For each hub i from 1 to N:

  • For each hub j from 1 to N:

  • Update dist[i][j] as the least of:

  • dist[i][j] (current distance)

  • dist[i] [k] dist[k] [j] (remove through hub k)

  • dist[j][i] fetched of turning around the edge from j to k dist[k][i] (separate through hub k with edge reversal)

  • Output the ultimate dist framework, which contains the most limited separations between all sets of hubs, considering the toll of edge inversion.

Example

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

const long long INF = 1e9;

void floydWarshall(vector<vector<long long>>& graph, int numNodes) {
    vector<vector<long long>> dist(graph); // Distance matrix initialized with the graph

    for (int nodeK = 0; nodeK < numNodes; nodeK++) {
        for (int nodeI = 0; nodeI < numNodes; nodeI++) {
            for (int nodeJ = 0; nodeJ < numNodes; nodeJ++) {
                dist[nodeI][nodeJ] = min(dist[nodeI][nodeJ], dist[nodeI][nodeK] + dist[nodeK][nodeJ] + graph[nodeJ][nodeK]);
            }
        }
    }

    // Storing the shortest distances in a string
    stringstream result;
    result << "Shortest distances between all pairs of nodes:" << endl;
    for (int i = 0; i < numNodes; i++) {
        for (int j = 0; j < numNodes; j++) {
            if (dist[i][j] == INF)
                result << "INF ";
            else
                result << dist[i][j] << " ";
        }
        result << endl;
    }

    // Print the result string
    cout << result.str();
}

int main() {
    int numNodes = 4; // Number of nodes

    // Adjacency matrix representation of the graph with edge weights and edge reversal costs
    vector<vector<long long>> graph = {
        {0, 5, INF, 10},
        {INF, 0, 3, INF},
        {INF, INF, 0, 1},
        {INF, INF, INF, 0}
    };

    floydWarshall(graph, numNodes);

    return 0;
}

Output

Shortest distances between all pairs of nodes:
0 5 INF 10 
INF 0 3 INF 
INF INF 0 1 
INF INF INF 0

Conclusion

This article examines the issue of finding the least far−fetched way to invert edges in order to set up a way between each match of hubs in a chart. It clarifies two approaches: the Covetous Calculation and the Floyd−Warshall Calculation with Edge Inversion. Taken a toll. The Ravenous Calculation centres on making locally optimal choices at each step to play down the general fetched of edge inversion. On the other hand, the Floyd−Warshall Calculation considers all sets of hubs and powerfully calculates the most brief ways of bookkeeping for the fetch of switching edges. These calculations provide solutions to the issue of setting up networks while minimising the overall fetch of edge inversion in a chart.

Updated on: 14-Jul-2023

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements