原题链接
- 题意:每次加一个数,要求最小 $sum max_{k=1}^{i} - min_{k=1}^{i},
- 题解:本来以为就是纯贪心,然后发现竟然是区间dp,就是先排完序,然后就加入然后取 (min)。
- 代码:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 2e3 + 9;
typedef unsigned long long ull;
const ll P = 131;
const ll mod = 100001333;
ll a[N];
ll dp[N][N];
void solve() {
ll n;cin >> n;
for (ll i = 1; i <= n; i ++ ) cin >> a[i];
sort(a + 1, a + 1 + n);
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][j-1] + a[j] - a[i], dp[i+1][j] + a[j] - a[i]);
}
}
cout << dp[1][n] << endl;
}
signed main() {
ios::sync_with_stdio(0);
ll t=1;
while (t--) solve();
return 0;
}