CF1509C.The Sports Festival

传统题 时间 1000 ms 内存 256 MiB 10 尝试 1 已通过 1 标签

The Sports Festival

CF1509C · The Sports Festival

英文原题面

Statement

The student council is preparing for the relay race at the sports festival. The council consists of nn members. They will run one after the other in the race, the speed of member ii is sis_i. The discrepancy did_i of the ii-th stage is the difference between the maximum and the minimum running speed among the first ii members who ran. Formally, if aia_i denotes the speed of the ii-th member who participated in the race, then $d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i)$. You want to minimize the sum of the discrepancies d1+d2++dnd_1 + d_2 + \dots + d_n. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?

Input

The first line contains a single integer nn (1n20001 \le n \le 2000)  — the number of members of the student council. The second line contains nn integers s1,s2,,sns_1, s_2, \dots, s_n (1si1091 \le s_i \le 10^9)  – the running speeds of the members.

Output

Print a single integer  — the minimum possible value of d1+d2++dnd_1 + d_2 + \dots + d_n after choosing the order of the members.

样例

样例 1

输入:

3
3 1 2

输出:

3

样例 2

输入:

1
5

输出:

0

样例 3

输入:

6
1 6 3 3 6 3

输出:

11

样例 4

输入:

6
104 943872923 6589 889921234 1000000000 69

输出:

2833800505

样例解释(英文原文)

In the first test case, we may choose to make the third member run first, followed by the first member, and finally the second. Thus a1=2a_1 = 2, a2=3a_2 = 3, and a3=1a_3 = 1. We have:

  • d1=max(2)min(2)=22=0d_1 = \max(2) - \min(2) = 2 - 2 = 0.
  • d2=max(2,3)min(2,3)=32=1d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1.
  • d3=max(2,3,1)min(2,3,1)=31=2d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2.

The resulting sum is d1+d2+d3=0+1+2=3d_1 + d_2 + d_3 = 0 + 1 + 2 = 3. It can be shown that it is impossible to achieve a smaller value. In the second test case, the only possible rearrangement gives d1=0d_1 = 0, so the minimum possible result is 00.

在线编程 IDE

建议全屏模式获得最佳体验