day17 1353 ski resort design (enumeration)

1353. Ski Resort Design

Farmer John’s farm has NNN mountain peaks, the height of each mountain is an integer.

In winter, John often organizes ski training camps on these mountains.

Unfortunately, starting next year, the country will implement a new tax law on ski resorts.

If the height difference between the highest peak and the lowest peak of the ski resort is greater than 17 171 7 , the state will collect taxes.

In order to avoid paying taxes, John decided to trim the height of these peaks.

Known, increase or decrease a mountain xxx unit height, it takesx 2 x^2x2 money.

John is only willing to change the height in integer units, and each mountain can only be changed once.

Excuse me, how much does John need to spend at least to make the height difference between the highest peak and the lowest peak not more than 17 1717

Input format The
first line contains the integer NNN

Next NNN lines, each line contains an integer, which represents the height of a mountain.

Output format
Output an integer that represents the least money spent.

Data range
1 ≤ N ≤ 1000 1 ≤ N ≤ 10001N1 0 0 0 , the
data guarantees that the initial height of each mountain is between0 ∼ 100 0 ∼ 1000Between 1 0 0 .

Input sample:

5
20
4
1
24
21

Sample output:

18

Sample explanation The
best solution is to increase the height of the mountain with a height of 1 by 3 units, and reduce the height of the mountain with a height of 24 by 3 units.

Ideas:

Situation 1:
Insert picture description here
Situation 2:
Insert picture description here
It can be concluded from the above that the height of the modified mountain must be 0~100within.
From this we can enumerate all possible intervals [i,i+17]:
[0,17]
[1,18]
...
[83,100]

  • Don't care if the current mountain is in the range.
  • If it is less than the left boundary of the interval, thencost += (i - arr[j]) * (i - arr[j])
  • If it is greater than the right boundary of the interval, thencost += (arr[j] - i - 17) * (arr[j] - i - 17)

Java code

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] arr = new int[n];
        for(int i = 0;i < n;i++){
    
    
            arr[i] = scanner.nextInt();
        }
		
		//初始将最小值设置的很大,方便后续对其更新
       int minCost = Integer.MAX_VALUE;
        for(int i = 0;i + 17 < 100;i++){
    
    //枚举每一个可能的区间
            int cost = 0;
            for(int j = 0;j < n;j++){
    
    
                if(arr[j] < i) cost += (i - arr[j]) * (i - arr[j]);
                if(arr[j] > i + 17) cost += (arr[j] - i - 17) * (arr[j] - i - 17);
            }
            //更新最小花费
            if(cost < minCost) minCost = cost;
        }
        System.out.println(minCost);
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/YouMing_Li/article/details/113872719