题目描述:
The student council is preparing for the relay race at the sports festival.
The council consists of n members. They will run one after the other in the race, the speed of member i is si. The discrepancy di of the i-th stage is the difference between the maximum and the minimum running speed among the first i members who ran. Formally, if ai denotes the speed of the i-th member who participated in the race, then di=max(a1,a2,…,ai)−min(a1,a2,…,ai)
You want to minimize the sum of the discrepancies d1+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?
输入描述:
The first line contains a single integer n (1≤n≤2000) — the number of members of the student council.
The second line contains n integers s1,s2,…,sn (1≤si≤109) – the running speeds of the members.
输出描述:
Print a single integer — the minimum possible value of d1+d2+⋯+dn after choosing the order of the members.
输入样例:
6
1 6 3 3 6 3
输出样例:
11
大概思路:
贪心部分:dn因为包含了所有数,所以一定是全数组的最值之差。我们可以优化的是前面,让前面的值尽可能地接近,才能减少sum。因此我们将数组sort,从某一位置出发,向两端步步扩大区间[l,r],计算sum。
dp部分:每一步扩大区间[l,r]有两种方式,l-1与r+1,此处不再符合贪心原则,而是dp。转移公式是dp[i][j]=min(dp[i+1][j],dp[i][j-1])+a[j]-a[i]。这是区间dp的退化版,先枚举长度,再枚举起点。转移来源要么i+1要么j-1,因此双重for循环内部不是o(n)的,而是o(1)的。
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=2020;
int a[N];
ll dp[N][N];
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
for(int d=2;d<=n;d++)
for(int i=0;i+d-1<n;i++)
{
int e=i+d-1;
dp[i][e]=min(dp[i+1][e],dp[i][e-1])+a[e]-a[i];
}
cout<<dp[0][n-1]<<endl;
return 0;
}