PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000356. GCD và cây khung nhỏ nhất (GCD and MST)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

GCD và cây khung nhỏ nhất (GCD and MST)

GCD and MST

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Given positive integers a1,…,ana_1,\ldots,a_n and pp, construct a weighted undirected graph on vertices 1,…,n1,\ldots,n. For every i<ji<j, add an edge of weight min⁡(ai,…,aj)\min(a_i,\ldots,a_j) if

gcd⁡(ai,…,aj)=min⁡(ai,…,aj).\gcd(a_i,\ldots,a_j)=\min(a_i,\ldots,a_j).

Additionally, add an edge of weight pp between each pair of consecutive vertices (i,i+1)(i,i+1). Parallel edges are allowed. Find the minimum spanning tree weight.

PHOJ format: Each input file contains one case, without the original Codeforces leading test count tt.

Input

  • First line: n,pn,p.
  • Second line: nn integers aia_i.

Output

A single integer: the MST total weight, potentially exceeding 32-bit limits.

Subtasks

  • Subtask 1 (20 points): 2<=n<=9;1<=p<=100;1<=ai<=1002 <= n <= 9; 1 <= p <= 100; 1 <= a_i <= 100.
  • Subtask 2 (30 points): 2<=n<=3000;1<=p<=106;1<=ai<=1062 <= n <= 3000; 1 <= p <= 10^6; 1 <= a_i <= 10^6.
  • Subtask 3 (50 points): 2<=n<=200000;1<=p<=109;1<=ai<=1092 <= n <= 200000; 1 <= p <= 10^9; 1 <= a_i <= 10^9.

Examples

Example 1

Input

2 5
10 10

Output

5

Explanation

The two vertices have a range-edge of weight 10 and an adjacent edge of weight 5; choose weight 5.

Example 2

Input

2 5
3 3

Output

3

Explanation

Since gcd(3,3)=min(3,3)=3, the edge of weight 3 is cheaper than weight 5.

Example 3

Input

4 5
5 2 4 9

Output

12

Explanation

Edges (1,2), (2,3), (3,4) may have weights 5,2,5, totaling the optimal 12.