import
java.util.Arrays;
import
java.util.Collections;
import
java.util.Vector;
public
class
MinimumSpanningTree {
static
Vector<Integer> rnk =
new
Vector<>(Collections.nCopies(
200001
,
0
));
static
Vector<Integer> parent =
new
Vector<>(Collections.nCopies(
200001
,
0
));
static
void
makeSet(
int
v) {
parent.set(v, v);
rnk.set(v,
0
);
}
static
int
findPar(
int
v) {
if
(v == parent.get(v))
return
v;
parent.set(v, findPar(parent.get(v)));
return
parent.get(v);
}
static
void
unionSets(
int
a,
int
b) {
a = findPar(a);
b = findPar(b);
if
(a != b) {
if
(rnk.get(a) < rnk.get(b))
Collections.swap(rnk, a, b);
parent.set(b, a);
if
(rnk.get(a) == rnk.get(b))
rnk.set(a, rnk.get(a) +
1
);
}
}
static
int
solve(Vector<Integer> a,
int
n,
int
k) {
Vector<Pair<Integer, Integer>> vp =
new
Vector<>(n);
for
(
int
i =
0
; i < n; i++) {
vp.add(
new
Pair<>(a.get(i), i));
vp.set(i,
new
Pair<>(a.get(i), i));
}
Collections.sort(vp, (x, y) -> x.first - y.first);
for
(
int
i =
0
; i < n; i++) {
makeSet(i);
}
int
j =
0
;
int
ans =
0
;
while
(j < n) {
int
idx = vp.get(j).second;
if
(vp.get(j).first > k)
break
;
int
i = idx +
1
;
int
currGcd = a.get(idx);
while
(i < n && currGcd == a.get(idx)) {
currGcd = gcd(currGcd, a.get(i));
if
(currGcd != a.get(idx))
break
;
int
x = findPar(idx);
int
y = findPar(i);
if
(x == y)
break
;
unionSets(x, y);
ans += a.get(idx);
i++;
}
i = idx -
1
;
currGcd = a.get(idx);
while
(i >=
0
&& currGcd == a.get(idx)) {
currGcd = gcd(currGcd, a.get(i));
if
(currGcd != a.get(idx))
break
;
int
x = findPar(idx);
int
y = findPar(i);
if
(x == y)
break
;
unionSets(x, y);
ans += a.get(idx);
i--;
}
j++;
}
for
(
int
i =
0
; i < n -
1
; i++) {
int
x = findPar(i);
int
y = findPar(i +
1
);
if
(x != y) {
unionSets(x, y);
ans += k;
}
}
return
ans;
}
static
int
gcd(
int
a,
int
b) {
return
b ==
0
? a : gcd(b, a % b);
}
public
static
void
main(String[] args) {
int
N =
4
, K =
5
;
Vector<Integer> a =
new
Vector<>(Arrays.asList(
3
,
2
,
6
,
3
));
int
result = solve(a, N, K);
System.out.println(result);
}
static
class
Pair<X, Y> {
X first;
Y second;
public
Pair(X first, Y second) {
this
.first = first;
this
.second = second;
}
}
}