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 sisi. The discrepancy didi 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 aiai denotes the speed of the ii-th member who participated in the race, then di=max(a1,a2,…,ai)−min(a1,a2,…,ai)di=max(a1,a2,…,ai)−min(a1,a2,…,ai).
You want to minimize the sum of the discrepancies d1+d2+⋯+dnd1+d2+⋯+dn. 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 (1≤n≤20001≤n≤2000) — the number of members of the student council.
The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤1091≤si≤109) – the running speeds of the members.
Output
Print a single integer — the minimum possible value of d1+d2+⋯+dnd1+d2+⋯+dn after choosing the order of the members.
Examples
input
Copy
3 3 1 2
output
Copy
3
input
Copy
1 5
output
Copy
0
input
Copy
6 1 6 3 3 6 3
output
Copy
11
input
Copy
6 104 943872923 6589 889921234 1000000000 69
output
Copy
2833800505
Note
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=2a1=2, a2=3a2=3, and a3=1a3=1. We have:
- d1=max(2)−min(2)=2−2=0d1=max(2)−min(2)=2−2=0.
- d2=max(2,3)−min(2,3)=3−2=1d2=max(2,3)−min(2,3)=3−2=1.
- d3=max(2,3,1)−min(2,3,1)=3−1=2d3=max(2,3,1)−min(2,3,1)=3−1=2.
The resulting sum is d1+d2+d3=0+1+2=3d1+d2+d3=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=0d1=0, so the minimum possible result is 00.
思路:
1,数据范围小=》维护区间上max和min的差值最小和=》区间dp=》需要状态和转移方程
2,dp[i][j]表示从i到j上的最小和,dp[i][j]=min(dp[i+1][j],dp[i][j-1])+a[j]-a[i];dp【i】【j】从i+1到j和i到j-1两个区间中的最小值得来,再加上i到j的max-min
2,len正向遍历,起点从头到尾,才能逐步更新
代码:
int dp[2200][2200];
int a[maxj];
void solve(){
int n;cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
}
sort(a+1,a+1+n);//维护一定区间上max和min差的最小和
for(int len=2;len<=n;++len){
for(int i=1;i<=n;++i){
int j=i+len-1;//i是左区间,j是右区间
dp[i][j]=min(dp[i+1][j],dp[i][j-1])+a[j]-a[i];
}
}cout<<dp[1][n]<<'\n';
}