time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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
题意
经典区间dp
给了一个有n个数,现在b[i]代表的是前i个数的最大值和最小值之差, 求b[1]+b[2]+…+b[n]的最小值
//区间dp
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#define INF 0x3f7f7f7f7f
const int maxn = 2005;
LL dp[maxn][maxn];
map<LL,int> mp;
vector<LL>vec;
int main()
{
int m;
cin >> m;
int n = 0;
for(int i = 0; i < m; i ++)
{
LL num;
cin >> num;
mp[num]++;
if(mp[num] == 1){
vec.push_back(num);
n++;
}
}
sort(vec.begin(),vec.end());
memset(dp,INF,sizeof(dp));
for(int i = 1; i <= n; i ++)
dp[i][i] = 0;
for(int len = 2; len <= n; len ++) //枚举长度
{
for(int i = 1; i+len-1 <= n; i ++) //枚举起点
{
int j = i+len -1;
dp[i][j] = min(dp[i+1][j]+fabs(vec[j-1]-vec[i-1])*mp[vec[i-1]],dp[i][j-1]+fabs(vec[j-1]-vec[i-1])*mp[vec[j-1]]);
}
}
cout << dp[1][n] <<endl;
return 0;
}