Codeforces Round #715 1509C - The Sports Festival 补题

1509C - The Sports Festival(记忆化+dp)

原题

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?

Input

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.

Output

Print a single integer — the minimum possible value of d1+d2+⋯+dn after choosing the order of the members.

Examples

input
3
3 1 2
output
3
input
1
5
output
0
input
6
1 6 3 3 6 3
output
11
input
6
104 943872923 6589 889921234 1000000000 69
output
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=2, a2=3, and a3=1. We have:

d1=max(2)−min(2)=2−2=0.
d2=max(2,3)−min(2,3)=3−2=1.
d3=max(2,3,1)−min(2,3,1)=3−1=2.
The resulting sum is d1+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=0, so the minimum possible result is 0.

题意

给定长度为n的数组a,规定每一项i(1≤i≤n),有di=max(a1,a2,…,ai)−min(a1,a2,…,ai) .改变数组顺序使得d1+d2+⋯+dn 的值最小

Solution

首先考虑最后一项dn,设数组a中所有元素最大值为amax,最小值为amin,则一定有dn=amax-amin

那么在已知dn 为定值的情况下,只需要使d1+d2+⋯+dn-1 的值最小。

那么此时先考虑dn-1,不难推知,要使dn-1 尽可能小,必须满足an=amaxan=amin.

反证:若 an!=amax && an!=amin ,则一定有dn-1=amax-amin,此时dn-1为最大值,不满足dn-1尽可能小

得出如上结论后,将数组a按升序排序,排序后a[n]={a1,a2,…,an},此时bn=an-a1,由上述证明知bn-1=min{an-a2,an-1-a1}.

在求得dn-1 的最小值后,同理可以根据使bn-1 最小时的状态继续求得bn-2 的最小值。

从而得出状态转移方程:dp(1,n)=(an-a1)+max{dp(2,n),dp(1,n-1)}

代码实现

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=2010;
int a[N],d[N][N];
int dp(int l,int r) //dp求解
{
    if(d[l][r]!=-1) return d[l][r]; //记忆化处理,处理后时间复杂度为O(n^2) 
    if(l==r) return 0;  //边界状态,只有一个数时d=0
    return d[l][r]=a[r]-a[l]+min(dp(l+1,r),dp(l,r-1));
}
signed main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+1+n);
    memset(d,-1,sizeof(d));
    cout<<dp(1,n);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值