由于题设中的区间长度为17,山的高度限定在0-100之间,所有可能的区间为0-17,1-18···83-100共84个,穷举算出最小值即可
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1005;
int arr[N];
int main() {
int n;
cin >> n;
for (int i = 0;i < n;i++) cin >> arr[i];
int cost = 0,ans = 1e9;
int l = 0,r = 17;
while (l <= 83) {
for (int i = 0;i < n;i++) {
if (arr[i] < l) {
cost += (l - arr[i]) * (l - arr[i]);
}
if (arr[i] > r) {
cost += (arr[i] - r) * (arr[i] - r);
}
}
ans = min(ans,cost);
l++;
r++;
cost = 0;
}
cout << ans << endl;
}