[go: up one dir, main page]

Open In App

Minimum cost to connect all houses in a city

Last Updated : 18 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 the absolute value of p.

Examples:

Input: houses[][] = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]
Output: 20
Explanation:


Connect house 1 (0, 0) with house 2 (2, 2) with cost = 4
Connect house 2 (2, 2) with house 3 (3, 10) with cost =9 
Connect house 2 (2, 2) with house 4 (5, 2) with cost =3 
At last, connect house 4 (5, 2) with house 5 (7, 0) with cost 4.
All the houses are connected now.
The overall minimum cost is 4 + 9 + 3 + 4 = 20.

Input: houses[][] = [[3, 12], [-2, 5], [-4, 1]]
Output: 18
Explanation:
Connect house 1 (3, 12) with house 2 (-2, 5) with cost = 12
Connect house 2 (-2, 5) with house 3 (-4, 1) with cost = 6
All the houses are connected now.
The overall minimum cost is 12 + 6 = 18.

Approach: The idea is to create a weighted graph from the given information with weights between any pair of edges equal to the cost of connecting them, say Ci i.e., the Manhattan distance between the two coordinates. Once the graph is generated, apply Kruskal’s Algorithm to find the Minimum Spanning Tree of the graph using Disjoint Set. Finally, print the minimum cost.

Below is the implementation of the above approach:

C++
// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

vector<int> parent, size;

// Utility function to find set of an
// element v using path compression
// technique
int find_set(int v)
{
    // If v is the parent
    if (v == parent[v])
        return v;

    // Otherwise, recursively
    // find its parent
    return parent[v]
           = find_set(parent[v]);
}

// Function to perform union
// of the sets a and b
int union_sets(int a, int b)
{
    // Find parent of a and b
    a = find_set(a);
    b = find_set(b);

    // If parent are different
    if (a != b) {

        // Swap Operation
        if (size[a] < size[b])
            swap(a, b);

        // Update parent of b as a
        parent[b] = a;
        size[a] += size[b];
        return 1;
    }

    // Otherwise, return 0
    return 0;
}

// Function to create a Minimum Cost
// Spanning tree for given houses
void MST(int houses[][2], int n)
{
    // Stores adjacency list of graph
    vector<pair<int, pair<int, int> > > v;

    // Traverse each coordinate
    for (int i = 0; i < n; i++) {

        for (int j = i + 1; j < n; j++) {

            // Find the Manhattan distance
            int p = abs(houses[i][0]
                        - houses[j][0]);

            p += abs(houses[i][1]
                     - houses[j][1]);

            // Add the edges
            v.push_back({ p, { i, j } });
        }
    }

    parent.resize(n);
    size.resize(n);

    // Sort all the edges
    sort(v.begin(), v.end());

    // Initialize parent[] and size[]
    for (int i = 0; i < n; i++) {
        parent[i] = i, size[i] = 1;
    }

    /// Stores the minimum cost
    int ans = 0;

    // Finding the minimum cost
    for (auto x : v) {

        // Perform the union operation
        if (union_sets(x.second.first,
                       x.second.second)) {
            ans += x.first;
        }
    }

    // Print the minimum cost
    cout << ans;
}

// Driver Code
int main()
{
    // Given houses
    int houses[][2] = { { 0, 0 }, { 2, 2 }, 
                        { 3, 10 }, { 5, 2 }, 
                        { 7, 0 }};

    int N = sizeof(houses)
            / sizeof(houses[0]);

    // Function Call
    MST(houses, N);

    return 0;
}
Java
// Java program for the above approach
import java.util.*;

// Class for DSU implementation
class DSU{
    
int parent[];
int rank[];

// Constructor to initialize DSU
DSU(int n)
{
    parent = new int[n];
    rank = new int[n];
    for(int i = 0; i < n; i++) 
    {
        parent[i] = -1;
        rank[i] = 1;
    }
}

// Utility function to find set of an
// element v using path compression
// technique
int find_set(int v)
{
    
    // If v is the parent
    if (parent[v] == -1)
        return v;
        
    // Otherwise, recursively
    // find its parent
    return parent[v] = find_set(parent[v]);
}

// Function to perform union
// of the sets a and b
void union_sets(int a, int b)
{
    
    // Find parent of a and b
    int p1 = find_set(a);
    int p2 = find_set(b);
    
    // If parent are different
    if (p1 != p2) 
    {
        
        // Swap Operation
        if (rank[p1] > rank[p2]) 
        {
            parent[p2] = p1;
            rank[p1] += rank[p2];
        }
        else 
        {
            parent[p1] = p2;
            rank[p2] += rank[p1];
        }
    }
}
}

class GFG{
    
// Function to create a Minimum Cost
// Spanning tree for given houses
static void MST(int houses[][], int n)
{
    int ans = 0;
    ArrayList<int[]> edges = new ArrayList<>();

    // Traverse each coordinate
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++) 
        {
            
            // Find the Manhattan distance
            int p = Math.abs(houses[i][0] - 
                             houses[j][0]);

            p += Math.abs(houses[i][1] - 
                          houses[j][1]);
                          
            // Add the edges
            edges.add(new int[]{ p, i, j });
        }
    }

    // Sorting arraylist using custome comparator
    // on the basis of weight i.e first element in
    // array object stored in Arraylist
    Collections.sort(edges, new Comparator<int[]>()
    {
        @Override public int compare(int[] o1, int[] o2)
        {
            return Integer.compare(o1[0], o2[0]);
        }
    });

    // Calling DSU class
    DSU d = new DSU(n);
    for(int i = 0; i < edges.size(); i++) 
    {
        int from = edges.get(i)[1];
        int to = edges.get(i)[2];

        // Checking if they lie in different component
        // or not i.e they have same parent or not in
        // DSU
        if (d.find_set(from) != d.find_set(to))
        {
            
            // Calling union_sets
            d.union_sets(from, to);
            ans += edges.get(i)[0];
        }
    }

    // Printing the minimum cost
    System.out.println(ans);
}

// Driver code
public static void main(String args[])
{
    
    // Graph in form of 2D array
    int houses[][] = { { 0, 0 }, { 2, 2 },
                       { 3, 10 }, { 5, 2 },
                       { 7, 0 } };
    int n = houses.length;
    
    // Function Call
    MST(houses, n);
}
}

// This code is contributed by Rahul Verma
Python
# Python3 program for the above approach
parent = [0] * 100
size = [0] * 100

# Utility function to find set of an
# element v using path compression
# technique
def find_set(v):
    
  #if v is parent
    if (v == parent[v]):
        return v

    # Otherwise, recursively
    # find its parent
    parent[v] = find_set(parent[v])

    return parent[v]

# Function to perform union
# of the sets a and b
def union_sets(a, b):
    
    # Find parent of a and b
    a = find_set(a)
    b = find_set(b)

    # If parent are different
    if (a != b):
        
        # Swap Operation
        if (size[a] < size[b]):
            a, b = b, a

        # Update parent of b as a
        parent[b] = a
        size[a] += size[b]
        return 1

    # Otherwise, return 0
    return 0

# Function to create a Minimum Cost
# Spanning tree for given houses
def MST(houses, n):
    
    # Stores adjacency list of graph
    v = []

    # Traverse each coordinate
    for i in range(n):
        for j in range(i + 1, n):

            # Find the Manhattan distance
            p = abs(houses[i][0] - 
                    houses[j][0])

            p += abs(houses[i][1] - 
                     houses[j][1])

            # Add the edges
            v.append([p, i, j])

    # Sort all the edges
    v = sorted(v)

    # Initialize parent[] and size[]
    for i in range(n):
        parent[i] = i
        size[i] = 1

    # Stores the minimum cost
    ans = 0

    # Finding the minimum cost
    for x in v:

        # Perform the union operation
        if (union_sets(x[1], x[2])):
            ans += x[0]
            
    # Print the minimum cost
    print(ans)

# Driver Code
if __name__ == '__main__':
    
    # Given houses
    houses = [ [ 0, 0 ], [ 2, 2 ],
               [ 3, 10 ], [ 5, 2 ],
               [ 7, 0 ] ]

    N = len(houses)

    # Function Call
    MST(houses, N)

# This code is contributed by mohit kumar 29
C#
using System;

class UnionFind
{
    private int[] parent;
    private int[] size;

    public UnionFind(int n)
    {
        parent = new int[n];
        size = new int[n];

        for (int i = 0; i < n; i++)
        {
            parent[i] = i;
            size[i] = 1;
        }
    }
    // Utility function to find set of an
//element v using path compression
// technique

    public int FindSet(int v)
    {
        //if v is parent
        if (v == parent[v])
        {
            return v;
        }
        //Otherwise, recursively
    //find its parent

        parent[v] = FindSet(parent[v]);
        return parent[v];
    }
    // Function to perform union
// of the sets a and b

    public int UnionSets(int a, int b)
    {
         // Find parent of a and b
        a = FindSet(a);
        b = FindSet(b);
 // If parent are different
        if (a != b)
        {
            if (size[a] < size[b])
            {
                 // Swap Operation
                int temp = a;
                a = b;
                b = temp;
            }
            //Update parent of b as a

            parent[b] = a;
            size[a] += size[b];
            return 1;
        }

        return 0;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int[][] houses = new int[][] {
            new int[] { 0, 0 },
            new int[] { 2, 2 },
            new int[] { 3, 10 },
            new int[] { 5, 2 },
            new int[] { 7, 0 }
        };

        int n = houses.Length;

        Tuple<int, int, int>[] edges = new Tuple<int, int, int>[(n * (n - 1)) / 2];
        int count = 0;
         // Traverse each coordinate

        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                int p = Math.Abs(houses[i][0] - houses[j][0]) +
                        Math.Abs(houses[i][1] - houses[j][1]);
                edges[count++] = Tuple.Create(p, i, j);
            }
        }
        // Sort all the edges

        Array.Sort(edges, (a, b) => a.Item1.CompareTo(b.Item1));

        UnionFind uf = new UnionFind(n);

        int ans = 0;

        foreach (var edge in edges)
        {
            if (uf.UnionSets(edge.Item2, edge.Item3) == 1)
            {
                ans += edge.Item1;
            }
        }

        Console.WriteLine(ans);
    }
}
JavaScript
<script>

// JavaScript program for the above approach
let parent = new Array(100).fill(0)
let size = new Array(100).fill(0)

// Utility function to find set of an
// element v using path compression
// technique
function find_set(v){
    
    // If v is the parent
    if (v == parent[v])
        return v

    // Otherwise, recursively
    // find its parent
    parent[v] = find_set(parent[v])

    return parent[v]
}

// Function to perform union
// of the sets a and b
function union_sets(a, b){
    
    // Find parent of a and b
    a = find_set(a)
    b = find_set(b)

    // If parent are different
    if (a != b){
        
        // Swap Operation
        if (size[a] < size[b]){
            a, b = b, a
        }

        // Update parent of b as a
        parent[b] = a
        size[a] += size[b]
        return 1
    }

    // Otherwise, return 0
    return 0
}

// Function to create a Minimum Cost
// Spanning tree for given houses
function MST(houses, n){
    
    // Stores adjacency list of graph
    let v = []

    // Traverse each coordinate
    for(let i=0;i<n;i++){
        for(let j=i+1;j<n;j++){

            // Find the Manhattan distance
            let p = Math.abs(houses[i][0] -
                    houses[j][0])

            p += Math.abs(houses[i][1] -
                    houses[j][1])

            // Add the edges
            v.push([p, i, j])
        }
    }

    // Sort all the edges
    v.sort((a,b)=>a[0]-b[0])

    // Initialize parent[] and size[]
    for(let i=0;i<n;i++){
        parent[i] = i
        size[i] = 1
    }

    // Stores the minimum cost
    let ans = 0

    // Finding the minimum cost
    for(let x of v){

        // Perform the union operation
        if (union_sets(x[1], x[2]))
            ans += x[0]

    }
            
    // Print the minimum cost
    document.write(ans,"</br>")
}

// Driver Code
    
// Given houses
let houses = [ [ 0, 0 ], [ 2, 2 ], [ 3, 10 ], [ 5, 2 ],[ 7, 0 ] ]

let N = houses.length

// Function Call
MST(houses, N)

// This code is contributed by shinjanpatra

</script>

Output
20

Time Complexity: O(N2)
Auxiliary Space: O(N2)



Similar Reads

Minimize cost of painting N houses such that adjacent houses have different colors
Given an integer N and a 2D array cost[][3], where cost[i][0], cost[i][1], and cost[i][2] is the cost of painting ith house with colors red, blue, and green respectively, the task is to find the minimum cost to paint all the houses such that no two adjacent houses have the same color. Examples: Input: N = 3, cost[][3] = {{14, 2, 11}, {11, 14, 5}, {
14 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 Cost of Flight ticket required to reach the city D
Given two integers N, D and an array A[] of size N where A[i] represents the population of ith city. For any city i, there are two flights to city (i+1) and to city (i+3), if they exist and the cost of a flight ticket between any two cities is the absolute difference between the population of those cities. Find the minimum cost to reach the Dth cit
7 min read
Minimum cost to connect all cities
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 t
14 min read
Minimum broadcast range required by M towers to reach N houses
Given an array a containing positions of N houses, and an array b containing positions of M radio towers, each placed along a horizontal line, the task is to find the minimum broadcast range such that each radio tower reaches every house.Examples: Input: a[] = {1, 5, 11, 20}, b[] = {4, 8, 15} Output: 5 Explanation: The minimum range required is 5,
8 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
Calculate total wall area of houses painted
Given integers N, L and W representing number of rows and length and width of houses in each row, and an array Heights[], representing the height of each house, the task is to find the total area of the outer walls required to be painted if the adjacent houses share a common wall. Examples: Input: N = 4, W = 1, L = 1, Heights[] = {1, 2, 3, 4}Output
7 min read
Maximum houses that can be painted continuously when the painting duration and date limit is given
Given an array arr[][] consisting of N pairs such that each pair {L, R} represents that ith house can be painted in L number of days before the Rth day, the task is to find the maximum number of house that can be painted continuously. Examples: Input: N = 4, paint[ ][ ] = [[1, 19], [2, 2], [4, 17], [1, 1]]Output: 3Explanation: Maximum of three hous
7 min read
Maximizing Robbery in Binary Tree Houses without Alerting Police
There are Houses arranged in the form of a Binary tree. There is only one entrance to the houses which is the root of a tree. It will automatically contact the police if two directly linked houses are broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police. E
11 min read
Finding Nearest Stores for each Houses
Given two arrays representing integer locations of stores[] and houses[] (each location in this problem is one-dimensional). The task is to find an integer array result[], where result[i] should denote the location of the store closest to the i-th house. If many stores are equidistant from a particular house, choose the store with the smallest nume
9 min read
Minimize supply of Corona Vaccines for N houses if a vaccine is sufficient for immediate neighbours
Geek has developed an effective vaccine for the coronavirus and wants to ensure that each of the n houses in Geek Land has access to it. The layout of Geek Land is represented as a binary tree, where each node corresponds to a house. Each house can be supplied with a single vaccine kit, which will be sufficient to cover that node, its parent, and i
15+ min read
Minimum bridges required to be crossed to reach Nth city
Given an integer N denoting the number of connected cities ( numbered from 1 to N ) and a 2D array arr[][] consisting of pairs connected to each other by bidirectional bridges. The task is to find the minimum the number of bridges required to be crossed to reach the city N from the city 1. Examples: Input: N = 3, M = 2, arr[][] = {{1, 2}, {2, 3}} O
9 min read
Finding Minimum travel time to Nearest city from Current location
Given an integer N representing the number of cities near you along with two arrays pos[] representing the position of the city and time[] representing the time required to move 1 unit of distance for a particular city, the task is to find the minimum time required to visit any city where you are currently at cur position. Examples: Input: N = 3, c
6 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
three90RightbarBannerImg