Minimum cost to reverse edges such that there is path between every pair of nodes Last Updated : 22 Dec, 2022 Comments Improve Suggest changes Like Article Like Report Given a connected, directional graph. Each node is connected to exactly two other nodes. There is a weight associated with each edge denoting the cost to reverse its direction. The task is to find the minimum cost to reverse some edges of the graph such that it is possible to go from each node to every other node. Examples: Input: 5 1 2 7 5 1 8 5 4 5 3 4 1 3 2 10 Output: 15 Input: 6 1 5 4 5 3 8 2 4 15 1 6 16 2 3 23 4 6 42 Output: 39 Approach: In order to reach from each node to every other node, the graph must form a ring i.e Direct all edges on it in one of 2 directions either clockwise or anti-clockwise. Let us denote the cost of redirecting all the clockwise edges to anticlockwise direction as cost1 and vice versa as cost2. The answer is clearly the minimum of these two costs.Maintain two boolean arrays start and end. The start and end arrays denote whether there is an edge starting from or ending at a given node. Whenever we encounter an edge going from node a to node b, we first check the condition if there is an edge already starting from node a or ending at node b. If there is an edge that satisfying the condition, the edge is in the opposite direction to the edge already present. In this case, we update cost2 and store the edge in the opposite direction. Otherwise, we update the cost1. This way we are able to maintain the costs of both orientations. Finally, print the minimum cost. Below is the implementation of the above approach: C++ // C++ code to find // the minimum cost to // reverse the edges #include <bits/stdc++.h> using namespace std; // Function to calculate // min cost for reversing // the edges int minCost(vector<vector<int> >& graph, int n) { int cost1 = 0, cost2 = 0; // bool array to mark // start and end node // of a graph bool start[n + 1] = { false }; bool end[n + 1] = { false }; for (int i = 0; i < n; i++) { int a = graph[i][0]; int b = graph[i][1]; int c = graph[i][2]; // This edge must // start from b and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must // start from a and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of // both possibilities return min(cost1, cost2); } // Driver code int main() { int n = 5; // Adjacency list representation // of a graph vector<vector<int> > graph = { { 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 } }; int ans = minCost(graph, n); cout << ans << '\n'; return 0; } Java // Java code to find the minimum cost to // reverse the edges class GFG { // Function to calculate min cost for // reversing the edges static int minCost(int[][] graph, int n) { int cost1 = 0, cost2 = 0; // bool array to mark start and // end node of a graph boolean []start = new boolean[n + 1]; boolean []end = new boolean[n + 1]; for (int i = 0; i < n; i++) { int a = graph[i][0]; int b = graph[i][1]; int c = graph[i][2]; // This edge must start from b // and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must start from a // and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of both possibilities return Math.min(cost1, cost2); } // Driver code public static void main(String[] args) { int n = 5; // Adjacency list representation // of a graph int [][]graph = {{ 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 }}; int ans = minCost(graph, n); System.out.println(ans); } } // This code is contributed by Rajput-Ji Python3 # Python code to find the minimum cost to # reverse the edges # Function to calculate min cost for # reversing the edges def minCost(graph, n): cost1, cost2 = 0, 0; # bool array to mark start and # end node of a graph start = [False]*(n + 1); end = [False]*(n + 1); for i in range(n): a = graph[i][0]; b = graph[i][1]; c = graph[i][2]; # This edge must start from b # and end at a if (start[a] or end[b]): cost2 += c; start[b] = True; end[a] = True; # This edge must start from a # and end at b else: cost1 += c; start[a] = True; end[b] = True; # Return minimum of both possibilities return min(cost1, cost2); # Driver code if __name__ == '__main__': n = 5; # Adjacency list representation # of a graph graph = [[ 1, 2, 7 ], [ 5, 1, 8 ], [ 5, 4, 5 ], [ 3, 4, 1 ], [ 3, 2, 10 ]]; ans = minCost(graph, n); print(ans); # This code is contributed by 29AjayKumar C# // C# code to find the minimum cost to // reverse the edges using System; class GFG { // Function to calculate min cost for // reversing the edges static int minCost(int[,] graph, int n) { int cost1 = 0, cost2 = 0; // bool array to mark start and // end node of a graph Boolean []start = new Boolean[n + 1]; Boolean []end = new Boolean[n + 1]; for (int i = 0; i < n; i++) { int a = graph[i, 0]; int b = graph[i, 1]; int c = graph[i, 2]; // This edge must start from b // and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must start from a // and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of both possibilities return Math.Min(cost1, cost2); } // Driver code public static void Main(String[] args) { int n = 5; // Adjacency list representation // of a graph int [,]graph = {{ 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 }}; int ans = minCost(graph, n); Console.WriteLine(ans); } } // This code is contributed by PrinciRaj1992 JavaScript <script> // JavaScript code to find // the minimum cost to // reverse the edges // Function to calculate // min cost for reversing // the edges function minCost(graph, n) { let cost1 = 0, cost2 = 0; // bool array to mark // start and end node // of a graph let start = new Array(n + 1).fill(false); let end = new Array(n + 1).fill(false); for (let i = 0; i < n; i++) { let a = graph[i][0]; let b = graph[i][1]; let c = graph[i][2]; // This edge must // start from b and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must // start from a and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of // both possibilities return Math.min(cost1, cost2); } // Driver code let n = 5; // Adjacency list representation // of a graph let graph = [ [1, 2, 7], [5, 1, 8], [5, 4, 5], [3, 4, 1], [3, 2, 10] ]; let ans = minCost(graph, n); document.write(ans + '<br>'); </script> Output: 15 Time Complexity: O(n)Auxiliary Space: O(n) Comment More infoAdvertise with us Next Article Minimum cost to reverse edges such that there is path between every pair of nodes P PrakharBansal1 Follow Improve Article Tags : Graph Algorithms DSA Arrays direct +1 More Practice Tags : AlgorithmsArraysGraph Similar Reads Minimum number of edges to be removed from given Graph such that no path exists between given pairs of vertices Given an undirected graph consisting of N valued over the range [1, N] such that vertices (i, i + 1) are connected and an array arr[] consisting of M pair of integers, the task is to find the minimum number of edges that should be removed from the graph such that there doesn't exist any path for eve 8 min read Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex âsâ to a given destination vertex âtâ. Simple Path is the path from one vertex to another such that no vertex is visited more than once. I 10 min read Minimum edges to reverse to make path from a source to a destination Given a directed graph with n nodes and m edges. A source node and a destination node are also given, we need to find how many edges we need to reverse in order to make at least 1 path from the source node to the destination node.Note: In case there is no way then return -1.Examples:  Input: n = 7, 15+ min read Check if given path between two nodes of a graph represents a shortest paths Given an unweighted directed graph and Q queries consisting of sequences of traversal between two nodes of the graph, the task is to find out if the sequences represent one of the shortest paths between the two nodes.Examples: Input: 1 2 3 4 Output: NOExplanation: The first and last node of the inpu 8 min read Minimum labelled node to be removed from undirected Graph such that there is no cycle Given an undirected graph of N nodes labelled from 1 to N, the task is to find the minimum labelled node that should be removed from the graph such that the resulting graph has no cycle. Note: If the initial graph has no cycle, i.e. no node needs to be removed, print -1. Examples: Input: N = 5, edge 15+ min read Find the shortest distance between any pair of two different good nodes Given a weighted undirected connected graph with N nodes and M edges. Some of the nodes are marked as good. The task is to find the shortest distance between any pair of two different good nodes.Note: Nodes marked as yellow in the below examples are considered to be good nodes. Examples: Input : Out 13 min read Minimum path need to reverse to reach each node in a tree from each vertex Given a directed tree consisting of N nodes valued from [0, N - 1] and M edges, the task is to find the minimum number of edges that need to reverse for each node X such that there is a path from node X to each vertex of the given Tree. Examples: Input: N = 6, edges[][] = {{0, 1}, {1, 3}, {2, 3}, {4 9 min read Minimum number of Edges to be added to a Graph to satisfy the given condition Given a graph consisting of N nodes numbered from 0 to N - 1 and M edges in the form of pairs {a, b}, the task is to find the minimum number of edges to be added to the graph such that if there exists a path from any node a to node b, then there should be paths from node a to nodes [ a + 1, a + 2, a 12 min read Shortest Path with even number of Edges from Source to Destination Given an undirected graph G, the task is to find the shortest path of even-length, given 1 as Source Node and N as Destination Node. Path length refers to the number of edges present in a path (not the cost of the path). Examples: Input: N = 5, G is given below: Output: 10 Explanation: All paths fro 13 min read Minimum nodes to be colored in a Graph such that every node has a colored neighbour Given a graph G with V nodes and E edges, the task is to colour no more than floor(V/2) nodes such that every node has at least one coloured node at a distance of atmost 1 unit. The distance between any two connected nodes of the graph is always exactly 1 unit. Print the nodes that need to be colore 9 min read Like