题目描述:
思路+AC代码:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define de(x) cout << x << " ";
#define sf(x) scanf("%d", &x);
#define Pu puts("");
const int N = 2e3 + 10;
int n, m;
int a[N], b[N];
int f[N][N]; // 表示已经安排了i个数字,且第i个数字为b[j]
int fun() {
for (int i = 1; i <= n; i++)
b[i] = a[i];
sort(b + 1, b + n + 1);
for (int i = 1; i <= n; i++) {
int minv = INT_MAX;
for (int j = 1; j <= n; j++) {
minv = min(minv, f[i - 1][j]);
// 记住这里的f[i][j]必须按照for循环,依次递增
f[i][j] = abs(a[i] - b[j]) + minv;
}
}
int res = INT_MAX;
for (int i = 1; i <= n; i++)
res = min(res, f[n][i]);
return res;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
sf(a[i]);
}
int r1 = fun();
// 这里进行翻转,实际上是考虑了两种情况
// a数组没有变化,b数组一直是从小到大的顺序
// 翻过来,相对于a数组,b数组一次从小一次从大进行排列
reverse(a + 1, a + n + 1);
int r2 = fun();
printf("%d\n", min(r1, r2));
return 0;
}