原题:
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.
题意和思路:
有n座山,如果最低和最高的山距离超过17就要交税,为了避免交税,对山进行处理,增高或减低,处理的成本是处理的高度x的平方。(都是整数)
解题思路:对山高度排序,将1-maxHeight之间的任意一个数作为标杆,对所有的山进行处理,超过十七就计算并加入成本,否者就不处理,最后将这maxHeight个标杆需要的成本进行比较,取最小的。
代码:
/*
ID:newyear111
PROG: skidesign
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>
using namespace std;
const int N=1005;
int H[N];
int n;
int main()
{
ifstream fin("skidesign.in");
ofstream fout("skidesign.out");
fin>>n;
for(int i=0;i<n;i++)
fin>>H[i];
sort(H,H+n);
//对山高排序
int cost=0x3f3f3f3f,mmax=H[n-1];
//以0-mmax的高度为处理其它山的标杆,差距大于十七就进行处理并计算成本,在最后和之前的最小成本比较,小就更新最小长成本
for(int i=0;i<=mmax;i++){
int sum=0;
for(int j=0;j<n;j++){
if(H[j]<i&&i-H[j]>17){
int t=i-H[j]-17;
sum+=t*t;
}
if(H[j]>i){
int c=H[j]-i;
sum+=c*c;
}
}
cost=min(sum,cost);
}
fout<<cost<<endl;
fin.close();
fout.close();
return 0;
}