There are n cities and there are roads in between some of the cities. Somehow all the roads are damaged simultaneously. We have to repair the roads to connect the cities again. There is a fixed cost to repair a particular road.
Input is in the form of edges {u, v, w} where, u and v are city indices. w is the cost to rebuild the road between u and v. Print out the minimum cost to connect all the cities by repairing roads.
Use a Min-Heap (Priority Queue) to always pick the cheapest edge.
Maintain a visited array to keep track of cities included in the MST.
Add edges to the MST until all cities are connected and return answer at last.
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to find the minimum cost to connect all the citiesintfindMST(intn,vector<vector<int>>&edges){vector<vector<pair<int,int>>>adj(n+1);// 1-based indexing// Convert edge list to adjacency list (1-based indexing adjustment)for(auto&edge:edges){intu=edge[0],v=edge[1],w=edge[2];adj[u].push_back({w,v});adj[v].push_back({w,u});}// Min-Heap (Priority Queue) to store {weight, node}priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;vector<bool>inMST(n+1,false);// To keep track of included nodespq.push({0,1});// Start from node **1** instead of 0intmstCost=0;// Store MST Costwhile(!pq.empty()){autotmp=pq.top();// Get the node with the smallest weightintw=tmp.first;intu=tmp.second;pq.pop();// If the node is already in MST, ignore itif(inMST[u])continue;inMST[u]=true;mstCost+=w;// Add weight to MST cost// Process all adjacent nodesfor(auto&it:adj[u]){intweight=it.first;intv=it.second;if(!inMST[v]){pq.push({weight,v});}}}returnmstCost;}// Driver functionintmain(){// Input: List of edges {u, v, weight} (1-based indexing)vector<vector<int>>city1={{1,2,1},{1,3,2},{1,4,3},{1,5,4},{2,3,5},{2,5,7},{3,4,6}};cout<<findMST(5,city1)<<endl;vector<vector<int>>city2={{1,2,1},{1,3,1},{1,4,100},{2,3,1},{4,5,2},{4,6,2},{5,6,2}};cout<<findMST(6,city2)<<endl;return0;}
Java
importjava.util.*;classPrimMST{staticclassEdgeimplementsComparable<Edge>{intnode,weight;Edge(intnode,intweight){this.node=node;this.weight=weight;}publicintcompareTo(Edgeother){returnthis.weight-other.weight;}}// Function to find the minimum cost to connect all the citiespublicstaticintfindMST(intn,int[][]edges){List<List<Edge>>adj=newArrayList<>();for(inti=0;i<=n;i++)adj.add(newArrayList<>());// 1-based indexing// Convert edge list to adjacency listfor(int[]edge:edges){intu=edge[0],v=edge[1],w=edge[2];adj.get(u).add(newEdge(v,w));adj.get(v).add(newEdge(u,w));}PriorityQueue<Edge>pq=newPriorityQueue<>();boolean[]inMST=newboolean[n+1];// 1-based indexingpq.add(newEdge(1,0));// Start from node 1intmstCost=0;while(!pq.isEmpty()){Edgeedge=pq.poll();intu=edge.node,weight=edge.weight;if(inMST[u])continue;inMST[u]=true;mstCost+=weight;for(Edgeneighbor:adj.get(u)){if(!inMST[neighbor.node]){pq.add(neighbor);}}}returnmstCost;}publicstaticvoidmain(String[]args){int[][]city1={{1,2,1},{1,3,2},{1,4,3},{1,5,4},{2,3,5},{2,5,7},{3,4,6}};System.out.println(findMST(5,city1));int[][]city2={{1,2,1},{1,3,1},{1,4,100},{2,3,1},{4,5,2},{4,6,2},{5,6,2}};System.out.println(findMST(6,city2));}}
Python
importheapq# Function to find the minimum cost to connect all the citiesdeffindMST(n,edges):adj=[[]for_inrange(n+1)]# 1-based indexing# Convert edge list to adjacency listforu,v,winedges:adj[u].append((w,v))adj[v].append((w,u))pq=[(0,1)]# (weight, node), start from node 1inMST=[False]*(n+1)# 1-based indexingmstCost=0whilepq:w,u=heapq.heappop(pq)ifinMST[u]:continueinMST[u]=TruemstCost+=wforweight,vinadj[u]:ifnotinMST[v]:heapq.heappush(pq,(weight,v))returnmstCost# Example usage with 1-based indexingcity1=[(1,2,1),(1,3,2),(1,4,3),(1,5,4),(2,3,5),(2,5,7),(3,4,6)]print(findMST(5,city1))city2=[(1,2,1),(1,3,1),(1,4,100),(2,3,1),(4,5,2),(4,6,2),(5,6,2)]print(findMST(6,city2))
C#
usingSystem;usingSystem.Collections.Generic;classPrimMST{classEdge:IComparable<Edge>{publicintNode,Weight;publicEdge(intnode,intweight){Node=node;Weight=weight;}publicintCompareTo(Edgeother){returnWeight.CompareTo(other.Weight);}}// Function to find the minimum cost to connect all the citiesstaticintFindMST(intn,List<int[]>edges){List<List<Edge>>adj=newList<List<Edge>>();for(inti=0;i<=n;i++)adj.Add(newList<Edge>());// 1-based indexing// Convert edge list to adjacency list (1-based)foreach(varedgeinedges){intu=edge[0],v=edge[1],w=edge[2];adj[u].Add(newEdge(v,w));adj[v].Add(newEdge(u,w));}// Using SortedSet as a MinHeap because C# PriorityQueue doesn't sort correctlySortedSet<(int,int)>pq=newSortedSet<(int,int)>();// (weight, node)bool[]inMST=newbool[n+1];// 1-based indexingpq.Add((0,1));// Start from node 1intmstCost=0;while(pq.Count>0){var(weight,u)=pq.Min;pq.Remove(pq.Min);// Remove the smallest elementif(inMST[u])continue;inMST[u]=true;mstCost+=weight;foreach(varneighborinadj[u]){if(!inMST[neighbor.Node]){pq.Add((neighbor.Weight,neighbor.Node));}}}returnmstCost;}staticvoidMain(){List<int[]>city1=newList<int[]>{newint[]{1,2,1},newint[]{1,3,2},newint[]{1,4,3},newint[]{1,5,4},newint[]{2,3,5},newint[]{2,5,7},newint[]{3,4,6}};Console.WriteLine(FindMST(5,city1));List<int[]>city2=newList<int[]>{newint[]{1,2,1},newint[]{1,3,1},newint[]{1,4,100},newint[]{2,3,1},newint[]{4,5,2},newint[]{4,6,2},newint[]{5,6,2}};Console.WriteLine(FindMST(6,city2));}}
JavaScript
classMinHeap{constructor(){this.heap=[];}push(item){this.heap.push(item);this.heap.sort((a,b)=>a[0]-b[0]);// Min-Heap sorting}pop(){returnthis.heap.shift();// Extract min element}size(){returnthis.heap.length;}}// Function to find the minimum cost to connect all the citiesfunctionfindMST(n,edges){letadj=Array.from({length:n+1},()=>[]);// 1-based indexing// Convert edge list to adjacency list (1-based)edges.forEach(([u,v,w])=>{adj[u].push([w,v]);adj[v].push([w,u]);});letpq=newMinHeap();letinMST=newArray(n+1).fill(false);// 1-based indexingpq.push([0,1]);// Start from node 1letmstCost=0;while(pq.size()>0){let[w,u]=pq.pop();if(inMST[u])continue;inMST[u]=true;mstCost+=w;for(let[weight,v]ofadj[u]){if(!inMST[v]){pq.push([weight,v]);}}}returnmstCost;}// Example Usage (1-based Indexing)letcity1=[[1,2,1],[1,3,2],[1,4,3],[1,5,4],[2,3,5],[2,5,7],[3,4,6]];console.log(findMST(5,city1));letcity2=[[1,2,1],[1,3,1],[1,4,100],[2,3,1],[4,5,2],[4,6,2],[5,6,2]];console.log(findMST(6,city2));
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.