Explanation
Like Kruskal's Algorithm, we generate our MST by adding edges greedily. Except the edges between any two adjacent elements in the array which cost , an edge only exists between and if the greatest common divisor of all elements in equals the minimum of the range .
As the cost of these edges is the minimum element of the range, let's iterate through all elements of the array in ascending order. This way, we guarantee that we always add edges of minimum cost. Let the current element be . There is an edge between and if divides . In that case, we can go further to and so on until no longer divides , or when the two elements are connected already. We apply the same operation in the other direction (, ...).
We stop the iteration when the cost of the edge (= the value of the element) is greater than . For all components that are not connected yet, we can simply connect them with cost . If we count the number of edges already added, and since a MST has edges, we can add to the answer.
Since the connected components are always a segment in the array, we only have to consider edges.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;using ll = long long;/** Solves a single test case. */void solve() {int n, p;cin >> n >> p;vector<int> arr(n);vector<int> indices(n);
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!