solution
刚开始贪了两拨,WA5两发,先排序,然后每次都是比较头尾,留少的。
然后学了一点区间DP
d p [ i ] [ j ] = m i n ( d p [ i ] [ j ] , m i n ( d p [ i + 1 ] [ j ] , d p [ i ] [ j − 1 ] ) + a [ j ] − a [ i ] ) dp[i][j]=min(dp[i][j],min(dp[i+1][j], dp[i][j-1])+a[j]-a[i]) dp[i][j]=min(dp[i][j],min(dp[i+1][j],dp[i][j−1])+a[j]−a[i])
code
/*SiberianSquirrel*//*CuteKiloFish*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = ll(1e9 + 7);
const ll INF = ll(1e18 + 10);
//VAR
ll dp[2010][2010];
void solve() {
int n, res, ans; cin >> n;
vector<ll> a(n + 1);
for(int i = 1; i <= n; ++ i) cin >> a[i];
sort(a.begin(), a.end());
for(int len = 2; len <= n; ++ len) {
for(int i = 1; i <= n - len + 1; ++ i) {
int j = i + len - 1;
dp[i][j] = INF;
}
}
for(int len = 2; len <= n; ++ len) {
for(int i = 1; i <= n - len + 1; ++ i) {
int j = i + len - 1;
dp[i][j] = min(dp[i][j], min(dp[i + 1][j], dp[i][j - 1]) + a[j] - a[i]);
}
}
cout << dp[1][n] << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
signed test_index_for_debug = 1;
char acm_local_for_debug = 0;
do {
if (acm_local_for_debug == '$') exit(0);
if (test_index_for_debug > 20)
throw runtime_error("Check the stdin!!!");
auto start_clock_for_debug = clock();
solve();
auto end_clock_for_debug = clock();
cout << "Test " << test_index_for_debug << " successful" << endl;
cerr << "Test " << test_index_for_debug++ << " Run Time: "
<< double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
cout << "--------------------------------------------------" << endl;
} while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
solve();
#endif
return 0;
}