問題 J: Ski Course Design----------------------------------思維

題目描述
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 x2 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.
輸入
Line 1:The integer N.
Lines 2…1+N:Each line contains the elevation of a single hill.
輸出
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.
樣例輸入 Copy
5
20
4
1
24
21
樣例輸出 Copy
18
提示
FJ’s farm has 5 hills, with elevations 1, 4, 20, 21, and 24.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 = 32 = 9). He shortens the hill of height 24 to height 21, also at a cost of 32 = 9.

題意:
農夫John(以後簡稱“FJ”)的農場裏有N(1 <= N <= 1,000)座小山,每座山都有一個在0 … 100範圍內的整數海拔高度。每年冬天,這些小山上充滿積雪時,FJ都會開設一個滑雪訓練營。不幸的是,FJ剛剛得知明年用作滑雪訓練營的農場將會被收取一項新稅。在仔細地閱讀了相關的法律條文後,他發現滑雪營地的官方定義中要求最高和最低的山丘高度差嚴格大於17。所以,如果FJ降低他最高小山的高度並升高矮小的小山,使之最高和最低小山的高度差不超過17,他就能夠避免交稅。如果改變一座山的高度x個單位需要花費x^2個單位的金錢,FJ最少需要花費多少錢來改造小山的高度?FJ只會將每座小山改變整數個單位的高度。

解析:
我們將所有山的高度全部調整到[l,r] 其中l+17==r 這樣可以一步到位 不用一個個的改山丘的高度

#include<bits/stdc++.h>
using namespace std;
int a[100005];
int n;
int main()
{
	cin>>n;
	int minn=0x3f3f3f3f;
	for(int i=1;i<=n;i++) cin>>a[i];
	sort(a,a+n);
	for(int i=0;i<=100-17;i++)
	{
		int ans=0;
		for(int j=1;j<=n;j++)
		{
				 if(a[j]<i) ans=ans+(a[j]-i)*(a[j]-i);
				 else if(a[j]>i+17) ans=ans+(a[j]-i-17)*(a[j]-i-17);
		}
		minn=min(minn,ans);
	}
	cout<<minn<<endl;
		
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章