Farmer John has N hills on his farm (1 <= N <= 1,000), each with an integer elevation in the range 0 .. 100. In the winter, since there is abundant snow on these hills, FJ routinely operates a ski training camp.
Unfortunately, FJ has just found out about a new tax that will be assessed next year on farms used as ski training camps. Upon careful reading of the law, however, he discovers that the official definition of a ski camp requires the difference between the highest and lowest hill on his property to be strictly larger than 17. Therefore, if he shortens his tallest hills and adds mass to increase the height of his shorter hills, FJ can avoid paying the tax as long as the new difference between the highest and lowest hill is at most 17.
If it costs x^2 units of money to change the height of a hill by x units, what is the minimum amount of money FJ will need to pay? FJ can change the height of a hill only once, so the total cost for each hill is the square of the difference between its original and final height. FJ is only willing to change the height of each hill by an integer amount.
PROGRAM NAME: skidesign
INPUT FORMAT:
Line 1: | The integer N. |
Lines 2..1+N: | Each line contains the elevation of a single hill. |
SAMPLE INPUT (file skidesign.in):
5 20 4 1 24 21
INPUT DETAILS:
FJ's farm has 5 hills, with elevations 1, 4, 20, 21, and 24.
OUTPUT FORMAT:
The minimum amount FJ needs to pay to modify the elevations of his hills so the difference between largest and smallest is at most 17 units.Line 1: |
SAMPLE OUTPUT (file skidesign.out):
18
OUTPUT DETAILS:
FJ keeps the hills of heights 4, 20, and 21 as they are. He adds mass to the hill of height 1, bringing it to height 4 (cost = 3^2 = 9). He shortens the hill of height 24 to height 21, also at a cost of 3^2 = 9.
分析:这道题的意思是输入一个数N代表有几座山,然后输入N个数,代表每座山的高度,最高山和最低山的高度差不能超过17,超过的费用为每改变x,花费x方。
思路:从最小的数开始,一直到最大的数-17,分两种情况计算,1.大于最小数+17。 2.小于最小数。没进行一个循环,最小数+1,(这样可以历遍所有情况)若是大于了最大数-17,则最大数-17到最大数都符合,就不用一直循环了!
/*
ID:
PROG: skidesign
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int N,s[1002],mid;
int big=0,small=110;
int ans=0xfffffff;
int main(){
freopen("skidesign.in","r",stdin);
freopen("skidesign.out","w",stdout);
cin>>N;
for(int i=0;i<N;i++){
cin>>s[i];
if(s[i]>big)big=s[i];
if(s[i]<small)small=s[i];
}
for(int i=small;i<=big-17;i++){
mid=0;
for(int j=0;j<N;j++){
if(s[j]>i+17)mid+=(s[j]-i-17)*(s[j]-i-17);
else if(s[j]<i)mid+=(i-s[j])*(i-s[j]);
}
ans=min(ans,mid);
}
cout<<ans<<endl;
}