The Wayback Machine - https://web.archive.org/web/20241123041959/https://www.geeksforgeeks.org/minimum-cost-connect-cities/
Open In App

Minimum cost to connect all cities

Last Updated : 06 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. Find out the minimum cost to connect all the cities by repairing roads. Input is in matrix(city) form, if city[i][j] = 0 then there is not any road between city i and city j, if city[i][j] = a > 0 then the cost to rebuild the path between city i and city j is a. Print out the minimum cost to connect all the cities. 
It is sure that all the cities were connected before the roads were damaged.

Examples: 

Input : {{0, 1, 2, 3, 4},
         {1, 0, 5, 0, 7},
         {2, 5, 0, 6, 0},
         {3, 0, 6, 0, 0},
         {4, 7, 0, 0, 0}};
Output : 10

min-cost

Input : {{0, 1, 1, 100, 0, 0},
         {1, 0, 1, 0, 0, 0},
         {1, 1, 0, 0, 0, 0},
         {100, 0, 0, 0, 2, 2},
         {0, 0, 0, 2, 0, 2},
         {0, 0, 0, 2, 2, 0}};
Output : 106

Method: Here we have to connect all the cities by path which will cost us least. The way to do that is to find out the Minimum Spanning Tree(MST) of the map of the cities(i.e. each city is a node of the graph and all the damaged roads between cities are edges). And the total cost is the addition of the path edge values in the Minimum Spanning Tree.

Prerequisite: MST Prim’s Algorithm

Implementation:

C++




// C++ code to find out minimum cost
// path to connect all the cities
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find out minimum valued node
// among the nodes which are not yet included in MST
int minnode(int n, int keyval[], bool mstset[]) {
  int mini = numeric_limits<int>::max();
  int mini_index;
 
  // Loop through all the values of the nodes
  // which are not yet included in MST and find
  // the minimum valued one.
  for (int i = 0; i < n; i++) {
    if (mstset[i] == false && keyval[i] < mini) {
      mini = keyval[i], mini_index = i;
    }
  }
  return mini_index;
}
 
// Function to find out the MST and
// the cost of the MST.
void findcost(int n, vector<vector<int>> city) {
 
  // Array to store the parent node of a
  // particular node.
  int parent[n];
 
  // Array to store key value of each node.
  int keyval[n];
 
  // Boolean Array to hold bool values whether
  // a node is included in MST or not.
  bool mstset[n];
 
  // Set all the key values to infinite and
  // none of the nodes is included in MST.
  for (int i = 0; i < n; i++) {
    keyval[i] = numeric_limits<int>::max();
    mstset[i] = false;
  }
 
  // Start to find the MST from node 0.
  // Parent of node 0 is none so set -1.
  // key value or minimum cost to reach
  // 0th node from 0th node is 0.
  parent[0] = -1;
  keyval[0] = 0;
 
  // Find the rest n-1 nodes of MST.
  for (int i = 0; i < n - 1; i++) {
 
    // First find out the minimum node
    // among the nodes which are not yet
    // included in MST.
    int u = minnode(n, keyval, mstset);
 
    // Now the uth node is included in MST.
    mstset[u] = true;
 
    // Update the values of neighbor
    // nodes of u which are not yet
    // included in MST.
    for (int v = 0; v < n; v++) {
 
      if (city[u][v] && mstset[v] == false &&
          city[u][v] < keyval[v]) {
        keyval[v] = city[u][v];
        parent[v] = u;
      }
    }
  }
 
  // Find out the cost by adding
  // the edge values of MST.
  int cost = 0;
  for (int i = 1; i < n; i++)
    cost += city[parent[i]][i];
  cout << cost << endl;
}
 
// Utility Program:
int main() {
 
  // Input 1
  int n1 = 5;
  vector<vector<int>> city1 = {{0, 1, 2, 3, 4},
                               {1, 0, 5, 0, 7},
                               {2, 5, 0, 6, 0},
                               {3, 0, 6, 0, 0},
                               {4, 7, 0, 0, 0}};
  findcost(n1, city1);
 
  // Input 2
  int n2 = 6;
  vector<vector<int>> city2 = {{0, 1, 1, 100, 0, 0},
                               {1, 0, 1, 0, 0, 0},
                               {1, 1, 0, 0, 0, 0},  
                               {100, 0, 0, 0, 2, 2},
                               {0, 0, 0, 2, 0, 2}, 
                               {0, 0, 0, 2, 2, 0}};
  findcost(n2, city2);
 
  return 0;
}


Java




// Java code to find out minimum cost
// path to connect all the cities
import java.util.*;
 
class GFG{
     
// Function to find out minimum valued node
// among the nodes which are not yet included
// in MST
static int minnode(int n, int keyval[],
                   boolean mstset[])
{
    int mini = Integer.MAX_VALUE;
    int mini_index = 0;
     
    // Loop through all the values of the nodes
    // which are not yet included in MST and find
    // the minimum valued one.
    for(int i = 0; i < n; i++)
    {
        if (mstset[i] == false &&
            keyval[i] < mini)
        {
            mini = keyval[i];
            mini_index = i;
        }
    }
    return mini_index;
}
 
// Function to find out the MST and
// the cost of the MST.
static void findcost(int n, int city[][])
{
     
    // Array to store the parent node of a
    // particular node.
    int parent[] = new int[n];
     
    // Array to store key value of each node.
    int keyval[] = new int[n];
     
    // Boolean Array to hold bool values whether
    // a node is included in MST or not.
    boolean mstset[] = new boolean[n];
 
    // Set all the key values to infinite and
    // none of the nodes is included in MST.
    for(int i = 0; i < n; i++)
    {
        keyval[i] = Integer.MAX_VALUE;
        mstset[i] = false;
    }
 
    // Start to find the MST from node 0.
    // Parent of node 0 is none so set -1.
    // key value or minimum cost to reach
    // 0th node from 0th node is 0.
    parent[0] = -1;
    keyval[0] = 0;
 
    // Find the rest n-1 nodes of MST.
    for(int i = 0; i < n - 1; i++)
    {
         
        // First find out the minimum node
        // among the nodes which are not yet
        // included in MST.
        int u = minnode(n, keyval, mstset);
     
        // Now the uth node is included in MST.
        mstset[u] = true;
     
        // Update the values of neighbor
        // nodes of u which are not yet
        // included in MST.
        for(int v = 0; v < n; v++)
        {
            if (city[u][v] > 0 &&
                 mstset[v] == false &&
                city[u][v] < keyval[v])
            {
                keyval[v] = city[u][v];
                parent[v] = u;
            }
        }
    }
 
    // Find out the cost by adding
    // the edge values of MST.
    int cost = 0;
    for(int i = 1; i < n; i++)
        cost += city[parent[i]][i];
         
    System.out.println(cost);
}
 
// Driver code
public static void main(String args[])
{
     
    // Input 1
    int n1 = 5;
    int city1[][] = { { 0, 1, 2, 3, 4 },
                      { 1, 0, 5, 0, 7 },
                      { 2, 5, 0, 6, 0 },
                      { 3, 0, 6, 0, 0 },
                      { 4, 7, 0, 0, 0 } };
                       
    findcost(n1, city1);
     
    // Input 2
    int n2 = 6;
    int city2[][] = { { 0, 1, 1, 100, 0, 0 },
                      { 1, 0, 1, 0, 0, 0 },
                      { 1, 1, 0, 0, 0, 0 },
                      { 100, 0, 0, 0, 2, 2 },
                      { 0, 0, 0, 2, 0, 2 },
                      { 0, 0, 0, 2, 2, 0 } };
                       
    findcost(n2, city2);
     
}
}
 
// This code is contributed by adityapande88


Python3




# Python3 code to find out minimum cost
# path to connect all the cities
 
# Function to find out minimum valued
# node among the nodes which are not
# yet included in MST
def minnode(n, keyval, mstset):
    mini = 999999999999
    mini_index = None
     
    # Loop through all the values of
    # the nodes which are not yet
    # included in MST and find the
    # minimum valued one.
    for i in range(n):
        if (mstset[i] == False and
            keyval[i] < mini):
            mini = keyval[i]
            mini_index = i
    return mini_index
 
# Function to find out the MST and
# the cost of the MST.
def findcost(n, city):
 
    # Array to store the parent
    # node of a particular node.
    parent = [None] * n
     
    # Array to store key value
    # of each node.
    keyval = [None] * n
     
    # Boolean Array to hold bool
    # values whether a node is
    # included in MST or not.
    mstset = [None] * n
     
    # Set all the key values to infinite and
    # none of the nodes is included in MST.
    for i in range(n):
        keyval[i] = 9999999999999
        mstset[i] = False
     
    # Start to find the MST from node 0.
    # Parent of node 0 is none so set -1.
    # key value or minimum cost to reach
    # 0th node from 0th node is 0.
    parent[0] = -1
    keyval[0] = 0
     
    # Find the rest n-1 nodes of MST.
    for i in range(n - 1):
     
        # First find out the minimum node
        # among the nodes which are not yet
        # included in MST.
        u = minnode(n, keyval, mstset)
     
        # Now the uth node is included in MST.
        mstset[u] = True
     
        # Update the values of neighbor
        # nodes of u which are not yet
        # included in MST.
        for v in range(n):
            if (city[u][v] and mstset[v] == False and
                city[u][v] < keyval[v]):
                keyval[v] = city[u][v]
                parent[v] = u
     
    # Find out the cost by adding
    # the edge values of MST.
    cost = 0
    for i in range(1, n):
        cost += city[parent[i]][i]
    print(cost)
 
# Driver Code
if __name__ == '__main__':
 
    # Input 1
    n1 = 5
    city1 = [[0, 1, 2, 3, 4],
             [1, 0, 5, 0, 7],
             [2, 5, 0, 6, 0],
             [3, 0, 6, 0, 0],
             [4, 7, 0, 0, 0]]
    findcost(n1, city1)
     
    # Input 2
    n2 = 6
    city2 = [[0, 1, 1, 100, 0, 0],
             [1, 0, 1, 0, 0, 0],
             [1, 1, 0, 0, 0, 0],
             [100, 0, 0, 0, 2, 2],
             [0, 0, 0, 2, 0, 2],
             [0, 0, 0, 2, 2, 0]]
    findcost(n2, city2)
 
# This code is contributed by PranchalK


C#




// C# code to find out minimum cost
// path to connect all the cities
using System;
 
class GFG{
 
// Function to find out minimum valued node
// among the nodes which are not yet included
// in MST
static int minnode(int n, int[] keyval,
                   bool[] mstset)
{
    int mini = Int32.MaxValue;
    int mini_index = 0;
 
    // Loop through all the values of the nodes
    // which are not yet included in MST and find
    // the minimum valued one.
    for(int i = 0; i < n; i++)
    {
        if (mstset[i] == false && keyval[i] < mini)
        {
            mini = keyval[i];
            mini_index = i;
        }
    }
    return mini_index;
}
 
// Function to find out the MST and
// the cost of the MST.
static void findcost(int n, int[,] city)
{
     
    // Array to store the parent node of a
    // particular node.
    int[] parent = new int[n];
 
    // Array to store key value of each node.
    int[] keyval = new int[n];
 
    // Boolean Array to hold bool values whether
    // a node is included in MST or not.
    bool[] mstset = new bool[n];
 
    // Set all the key values to infinite and
    // none of the nodes is included in MST.
    for(int i = 0; i < n; i++)
    {
        keyval[i] = Int32.MaxValue;
        mstset[i] = false;
    }
 
    // Start to find the MST from node 0.
    // Parent of node 0 is none so set -1.
    // key value or minimum cost to reach
    // 0th node from 0th node is 0.
    parent[0] = -1;
    keyval[0] = 0;
 
    // Find the rest n-1 nodes of MST.
    for(int i = 0; i < n - 1; i++)
    {
         
        // First find out the minimum node
        // among the nodes which are not yet
        // included in MST.
        int u = minnode(n, keyval, mstset);
 
        // Now the uth node is included in MST.
        mstset[u] = true;
 
        // Update the values of neighbor
        // nodes of u which are not yet
        // included in MST.
        for(int v = 0; v < n; v++)
        {
            if (city[u, v] > 0 && mstset[v] == false &&
                city[u, v] < keyval[v])
            {
                keyval[v] = city[u, v];
                parent[v] = u;
            }
        }
    }
 
    // Find out the cost by adding
    // the edge values of MST.
    int cost = 0;
    for(int i = 1; i < n; i++)
        cost += city[parent[i], i];
 
    Console.WriteLine(cost);
}
 
// Driver code
public static void Main(string[] args)
{
 
    // Input 1
    int n1 = 5;
    int[,] city1 = { { 0, 1, 2, 3, 4 },
                     { 1, 0, 5, 0, 7 },
                     { 2, 5, 0, 6, 0 },
                     { 3, 0, 6, 0, 0 },
                     { 4, 7, 0, 0, 0 } };
 
    findcost(n1, city1);
 
    // Input 2
    int n2 = 6;
    int[,] city2 = { { 0, 1, 1, 100, 0, 0 },
                     { 1, 0, 1, 0, 0, 0 },
                     { 1, 1, 0, 0, 0, 0 },  
                     { 100, 0, 0, 0, 2, 2 },
                     { 0, 0, 0, 2, 0, 2 },  
                     { 0, 0, 0, 2, 2, 0 } };
 
    findcost(n2, city2);
}
}
 
// This code is contributed by ukasp


Javascript




<script>
 
// Javascript code to find out minimum cost
// path to connect all the cities
   
// Function to find out minimum valued node
// among the nodes which are not yet included
// in MST
function minnode(n, keyval,
                   mstset)
{
    let mini = Number.MAX_VALUE;
    let mini_index = 0;
      
    // Loop through all the values of the nodes
    // which are not yet included in MST and find
    // the minimum valued one.
    for(let i = 0; i < n; i++)
    {
        if (mstset[i] == false &&
            keyval[i] < mini)
        {
            mini = keyval[i];
            mini_index = i;
        }
    }
    return mini_index;
}
  
// Function to find out the MST and
// the cost of the MST.
function findcost(n, city)
{
      
    // Array to store the parent node of a
    // particular node.
    let parent = Array(n).fill(0);
      
    // Array to store key value of each node.
    let keyval = Array(n).fill(0);
      
    // Boolean Array to hold bool values whether
    // a node is included in MST or not.
    let mstset = Array(n).fill(0);
  
    // Set all the key values to infinite and
    // none of the nodes is included in MST.
    for(let i = 0; i < n; i++)
    {
        keyval[i] = Number.MAX_VALUE;
        mstset[i] = false;
    }
  
    // Start to find the MST from node 0.
    // Parent of node 0 is none so set -1.
    // key value or minimum cost to reach
    // 0th node from 0th node is 0.
    parent[0] = -1;
    keyval[0] = 0;
  
    // Find the rest n-1 nodes of MST.
    for(let i = 0; i < n - 1; i++)
    {
          
        // First find out the minimum node
        // among the nodes which are not yet
        // included in MST.
        let u = minnode(n, keyval, mstset);
      
        // Now the uth node is included in MST.
        mstset[u] = true;
      
        // Update the values of neighbor
        // nodes of u which are not yet
        // included in MST.
        for(let v = 0; v < n; v++)
        {
            if (city[u][v] > 0 &&
                 mstset[v] == false &&
                city[u][v] < keyval[v])
            {
                keyval[v] = city[u][v];
                parent[v] = u;
            }
        }
    }
  
    // Find out the cost by adding
    // the edge values of MST.
    let cost = 0;
    for(let i = 1; i < n; i++)
        cost += city[parent[i]][i];
          
    document.write(cost + "<br/>") ;
}
 
// driver code
 
        // Input 1
    let n1 = 5;
    let city1 =     [[ 0, 1, 2, 3, 4 ],
                      [ 1, 0, 5, 0, 7 ],
                      [ 2, 5, 0, 6, 0 ],
                      [ 3, 0, 6, 0, 0 ],
                      [ 4, 7, 0, 0, 0 ]];
                        
    findcost(n1, city1);
      
    // Input 2
    let n2 = 6;
    let city2 = [[ 0, 1, 1, 100, 0, 0 ],
                      [ 1, 0, 1, 0, 0, 0 ],
                      [ 1, 1, 0, 0, 0, 0 ],
                      [ 100, 0, 0, 0, 2, 2 ],
                      [ 0, 0, 0, 2, 0, 2 ],
                      [ 0, 0, 0, 2, 2, 0 ]];
                        
    findcost(n2, city2);
     
</script>


Output: 

10
106

 

Time Complexity: The outer loop(i.e. the loop to add new node to MST) runs n times and in each iteration of the loop it takes O(n) time to find the min node and O(n) time to update the neighboring nodes of u-th node. Hence the overall complexity is O(n2)

Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Connecting all Cities With Minimum Cost
Given n cities labeled 1 to n and an array of connections[] where connections[i] = [xi, yi, costi] represent that the cost of connecting city xi and city yi (bidirectional connection) is costi. The task is to find the minimum cost to connect all the cities with at least one path between each pair. If it's impossible to connect all the cities, retur
10 min read
Minimize cost to connect the graph by connecting any pairs of vertices having cost at least 0
Given a disconnected graph G with N vertices and M edges and an array cost[] corresponding to each vertex, the task is to find the minimum cost to make the graph by connecting any pairs of vertices having the cost of vertices at least 0 and the cost of connecting those pair of vertices is the sum of the cost of individual vertices. If it is impossi
15+ min read
Minimum possible travel cost among N cities
There are N cities situated on a straight road and each is separated by a distance of 1 unit. You have to reach the (N + 1)th city by boarding a bus. The ith city would cost of C[i] dollars to travel 1 unit of distance. In other words, cost to travel from the ith city to the jth city is abs(i - j ) * C[i] dollars. The task is to find the minimum co
6 min read
Minimum cost to connect all houses in a city
Given a 2D array houses[][] consisting of N 2D coordinates {x, y} where each coordinate represents the location of each house, the task is to find the minimum cost to connect all the houses of the city. Cost of connecting two houses is the Manhattan Distance between the two points (xi, yi) and (xj, yj) i.e., |xi - xj| + |yi - yj|, where |p| denotes
10 min read
Minimum cost to connect weighted nodes represented as array
Given an array of N elements(nodes), where every element is weight of that node.Connecting two nodes will take a cost of product of their weights.You have to connect every node with every other node(directly or indirectly).Output the minimum cost required.Examples: Input : a[] = {6, 2, 1, 5} Output : 13 Explanation : Here, we connect the nodes as f
4 min read
Connect n ropes with minimum cost
Given are N ropes of different lengths, the task is to connect these ropes into one rope with minimum cost, such that the cost to connect two ropes is equal to the sum of their lengths. Examples: Input: arr[] = {4,3,2,6} , N = 4Output: 29Explanation:  First, connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6, and 5. Now conne
6 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Minimum Cost using Dijkstra by Modifying Cost of an Edge
Given an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that we can reduce the cost of any edge lets say, C to
15 min read
Minimum Cost To set Digital Clock Timer with given movement and push cost
Given integers A, B and N. The task is to minimize the cost to set N seconds in a digital clock where time is represented in the following format: at most 99 minutes and 99 secondsat least 1 secondThe first two digits represent minutes and the last two minutes represent seconds.It prepends 0 if less than 4 digits are pressed to set time A is the co
14 min read
Minimum cost to complete given tasks if cost of 1, 7 and 30 days are given
Given a sorted array arr[] consisting of N positive integers such that arr[i] represent the days in which a worker will work and an array cost[] of size 3 representing the salary paid to the workers for 1 day, 7 days and 30 days respectively, the task is to find the minimum cost required to have a worker for all the given days in arr[]. Examples: I
15+ min read
Minimize cost to convert all 0s to 1s with cost of converting 0s group be X and that of 1 be X/3
Given binary string str, consisting of only two characters '1' and '0', and an integer X, the task is to calculate the minimum cost to convert all the characters to '1'. The cost to convert one '0' to '1' is given as X and the cost to convert one '1' to '0' is X / 3. If a '0' is converted to '1' then all the 0s adjacently connected to it as a group
9 min read
Count ways to traverse all N cities when each city is traversed K times
For N given cities, find how many ways a driver can traverse through them so that each town is visited exactly K times. From each city he can go to every other city (except the city which is already in it). Example: Input: N = 3, K = 1Output: 6Explanation: The possible paths are 1 -> 2 -> 31 -> 3 -> 22 -> 1 -> 32 -> 3 -> 13
15+ min read
Minimum number of Straight Lines to connect all the given Points
Given 2d integer array arr[][] containing N coordinates each of type {X, Y}, the task is to find the minimum number of straight lines required to connect all the points of the array. Examples: Input: arr[][] = {{1, 7}, {2, 6}, {3, 5}, {4, 4}, {5, 4}, {6, 3}, {7, 2}, {8, 1}}Output: 3Explanation: The diagram represents the input points and the minimu
8 min read
Minimum length of wire needed to connect all points who have value as 0 with at least one point with value 1.
Given two arrays Point[] and Value[] of length N, where Point[] represents the position of N points on a horizontal line. Then your task is to output the minimum length of line needed to connect all points having Value[i] = 0 with at least one point having Value[i] = 1, directly or indirectly. Note: There will be at least one point with value = 1.
12 min read
Minimize cost to sort an Array by swapping any pair of element (X, Y) with cost as (X + Y)
Given an array arr[] consisting of N integers, the task is to find the minimum cost to sort the given array arr[] in ascending order by swapping any pair of elements (X, Y) such that the cost of swapping is (X + Y). Examples: Input: arr[] = {3, 2, 1}Output: 4Explanation:Following are the swapping of array elements performed to sort the array: Swapp
13 min read
Minimize cost to empty given array where cost of removing an element is its absolute difference with Time instant
Given an array arr[] consisting of N integers, the task is to find the minimum cost to remove all elements from the array such that the cost of removing any element is the absolute difference between the current time instant T (initially 1) and the array element arr[i] i.e., abs(T - arr[i]) where T. Examples: Input: arr[] = {3, 6, 4, 2}Output: 0Exp
9 min read
Minimize cost to sort the Array by moving elements with cost as the value itself
Given an array arr[] of N positive integers, the task is to find the minimum cost to sort the given array by moving an array element to any position such that the cost of moving that element is the value of that element. Examples: Input: arr[] = {7, 1, 2, 3}Output: 6Explanation:Following are the possible set of moves to sort the array with minimum
9 min read
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset
Given an array arr[] of size N and a positive integer K, the task is to find the minimum possible cost to split the array into K subsets, where the cost of ith element ( 1-based indexing ) of each subset is equal to the product of that element and i. Examples: Input: arr[] = { 2, 3, 4, 1 }, K = 3 Output: 11 Explanation: Split the array arr[] into K
7 min read
Maximize cost of segment having weight at most K from given weight and cost of N items
Given two arrays W[] and C[] containing weight and cost of N (1 to N) items respectively, and an integer K, find a segment from 1 to N, such that the total weight of the segment is at most K and the total cost is maximum. Print the cost of this segment. Examples: Input: N = 6, K = 20, W[] = {9, 7, 6, 5, 8, 4}, C[] = {7, 1, 3, 6, 8, 3}Output: 17Expl
12 min read
Minimize cost to travel from source to destination in a Matrix based on given row change and column change cost
Given an M*N grid, and given an array startPos[], indicating that the starting position is the cell (startPos[0], startPos[1]) and the array homePos[] indicating its destination is at the cell's (homePos[0], homePos[1]). From any cell movement is allowed only in four directions: left, right, up, and down, and cannot go outside the boundary. There a
7 min read
Minimize cost by splitting given Array into subsets of size K and adding highest K/2 elements of each subset into cost
Given an array arr[] of N integers and an integer K, the task is to calculate the minimum cost by spilling the array elements into subsets of size K and adding the maximum ⌈K/2⌉ elements into the cost. Note: ⌈K/2⌉ means ceiling value of K/2. Examples: Input: arr[] = {1, 1, 2, 2}, K = 2Output: 3Explanation: The given array elements can be divided in
5 min read
Minimize cost to traverse the Arrays with given Array switching cost
Given three arrays A[], B[] and C[] of size N each and two integers X and Y, the task is to, find the minimum cost to reach the end of the arrays with the following conditions: Select one of the three elements at every index. For switching from 1st array to 2nd or vice versa, extra X points are required and For switching from 2nd array to 3rd or vi
8 min read
Minimize cost to buy N elements using given cost Array
Given 2 arrays num[] and cost[] containing the number of elements and the cost to buy that many elements respectively. {i.e. cost[i] is the cost to buy num[i] elements}. The task is to minimize the cost to buy exactly N elements. Examples: Input: num[] = [1, 2, 10, 50], cost[] = [400, 750, 3250, 15000], N = 7Output: 2650Explanation: The minimum amo
15+ min read
Minimize cost to reach bottom right from top left corner of Matrix with given separate cost for each move
Given an integer N and three N x N matrices X[][], Y[][], and Z[][], the task is to calculate the minimum cost required to reach the bottom right from the top left of the matrix using the following moves: Move to a cell in the right direction from (i, j) which will cost X[i][j].Move to a cell in the downward direction from (i, j) which will cost Y[
15+ min read
Single source shortest path between two cities
Given a graph of N Nodes and E edges in form of {U, V, W} such that there exists an edge between U and V with weight W. You are given an integer K and source src and destination dst. The task is to find the cheapest cost path from given source to destination from K stops.Examples: Input: N = 3, edges = [[0, 1, 100], [1, 2, 100], [0, 2, 500]], src =
15+ min read
Minimize total time taken by two persons to visit N cities such that none of them meet
Given an array arr[] of size N, where arr[i] is the time required to visit ith city, the task is to find the minimum total time required to visit all N cities by two persons such that none of them meet in any of the cities. Examples: Input: arr[] = {2, 8, 3}Output: 16Explanation:Visiting cities in below given order will take minimum time:First pers
5 min read
Treasure and Cities
Given n cities: x1, x2, …… xn: each associated with T[i] (treasure) and C[i] (color). You can choose to visit a city or skip it. Only moving in the forward direction is allowed.When you visit a city you receive the following amount: A*T[i] if the color of visited city is the same as color of previously visited cityB*T[i] if this is the first city v
15+ min read
Shortest path between two cities without running out of fuel
Given a country with N cities connected by M bi-directional roads given in the form of 2D array roads[][], where P cities have fuel stations and (N - P) cities do not. The task is to compute the shortest path from City A to City B, such that a car with maximum fuel capacity of "capacity" can travel without running out of fuel. Note: 1 unit of fuel
10 min read
Minimum cost to equal all elements of array using two operation
Given an array arr[] of n positive integers. There are two operations allowed: Operation 1 : Pick any two indexes, increase value at one index by 1 and decrease value at another index by 1. It will cost a. Operation 2 : Pick any index and increase its value by 1. It will cost b. The task is to find the minimum cost to make all the elements equal in
8 min read
Minimum cost to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to make all values of this array equal to some integer value with minimum cost after performing below operations any number of times (possibly zero). Reduce the array element by 2 or increase it by 2 with zero cost.Reduce the array element by 1 or increase it by 1 with a unit cost.
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg