![]() |
VOOZH | about |
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:
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 = 10Input: 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
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:
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. ans = 0.idx, set j to idx+1 and curr_gcd to a[idx].a[idx]) to the total ans and increment j, or else break.ans.Below is the implementation of above approach:
10
Time Complexity: O(N logN), where N is the size of the input array arr[].
Auxiliary Space: O(N)