CF 1509C. The Sports Festifal

The Sports Festifal

题意

给定长度为 \(n\) 的数组,定义 \(S_i = \max_{j=1}^{i}a[j] - \min_{j=1}^{i}a[j]\),重新排列数组,使得 \(\sum_{i=1}^{n}S_i\) 最小。

分析

因为要构造最小,那么对于区间 [l, r] 而言,最小的或者最大的一定要放到最后,由于 \(1 \le n \le 2000\) ,考虑区间DP,状态转移方程为:

\[f[l, r] = min(f[l+1, r], f[l, r-1]) + a[j] - a[i] \]

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int N = 2010;
ll f[N][N];
int a[N];

void solve ()
{
    int n; cin >> n;
    rep(i, 1, n) cin >> a[i];
    sort(a+1, a+n+1);
    for (int len = 2; len <= n; len ++ )
        for (int l = 1; l + len - 1 <= n; l ++ )
        {
            int r = l + len - 1;
            f[l][r] = min(f[l+1][r], f[l][r-1]) + a[r] - a[l];
        }
    cout << f[1][n] << endl;
}

signed main ()
{
    cout.tie(0)->sync_with_stdio(false);
    solve();
    return 0;
}
posted @ 2021-11-20 13:13  Horb7  阅读(31)  评论(0编辑  收藏  举报