#P7789. Minimum Cost to Connect Cards
Minimum Cost to Connect Cards
Minimum Cost to Connect Cards
You are given N cards. Each card contains an integer value, \(P_i\). You can connect any two cards at a cost of \(\min(P_a \bmod P_b,\; P_b \bmod P_a)\). The goal is to connect all cards (i.e. form a spanning tree) such that the total cost is minimized.
Note: The operation \(a \bmod b\) denotes the remainder when \(a\) is divided by \(b\), and the cost for connecting card a and card b is defined as \(\min(P_a \bmod P_b,\; P_b \bmod P_a)\). You need to compute the minimum total cost required to connect all of the cards.
inputFormat
The first line contains a single integer \(N\) (with \(N \ge 2\)), representing the number of cards.
The second line contains \(N\) space-separated integers \(P_1, P_2, \ldots, P_N\), where \(P_i\) denotes the value on the i-th card.
outputFormat
Output a single integer, the minimum total cost to connect all the cards.
sample
3
4 10 12
2