VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-mst-from-gcd/

⇱ Construct MST from GCD - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct MST from GCD

Last Updated : 23 Jul, 2025

Given an array arr[] of N integers. and an integer K. Construct a weighted undirected graph of N vertices numbered from 0 to N-1. An edge between the vertices i and j (j>i) is added if any one of the following conditions is satisfied:

  1. If j = i + 1, add an edge of weight K between vertices i and j.
  2. If min(ai , ai+1 ,....., aj) = gcd(ai , ai+1 ,....., aj), add an edge of weight min(ai , ai+1 ,....., aj) between vertices i and j.

The task is to determine the MST(Minimum Spanning Tree) of the resultant graph.

Examples:

Input: N=4, K=5, arr = [3, 2, 6, 3]
Output: 10
Explanation: The image shows that the cost of MST is 5 + 2 + 3 = 10

👁 MST_1

Input: N=4, K=3, arr = [5, 10, 2, 3]
Output: 8
Explanation: The image shows that the cost of MST is 3 + 2 + 3 = 8

👁 MST_2

Approach: The problem can be solved using the following approach:

The idea is to consider the edges which have a smaller weight first. This can be done by storing array along with its index and then sort it according to the value. For any element with index idx, we will have to move left and right separately. If we add a new element with index j while moving left or right, the condition gcd(curr_gcd, a[j]) = a[idx] should be satisfied. If it is satisfied, we can add an edge of weight a[idx] between vertices idx and j. If idx and j are already in same Connected Component then no edge will be added and we will simply break and repeat the process for remaining elements.

Follow the steps to solve the above problem:

  • Create a vector of pairs vp where each pair consists of the array element and its index and sort this vector vp in ascending order based on the array values.
  • Initialize total weight of the Minimum Spanning Tree (MST) as ans = 0.
  • Iterate through sorted elements:
    • Get the index of the current element as idx, set j to idx+1 and curr_gcd to a[idx].
    • While j is less than the size of the array:
      • Update the curr_gcd to gcd(curr_gcd, a[j]).
      • If curr_gcd is equal to a[idx] then, check whether vertices idx and j are in same connected component (this can be done using Disjoint Set Union). If they are not in same component add the edge weight (a[idx]) to the total ans and increment j, or else break.
    • Repeat the similar logic for j=idx-1.
  • Iterate through i=0 to n-1,
    • If vertices i and i+1 are not in same component add the edge weight k to the total ans.
  • Return ans.

Below is the implementation of above approach:


Output
10

Time Complexity: O(N logN), where N is the size of the input array arr[].
Auxiliary Space: O(N)

Comment