Kevin and Sticks

3.9

16 votes
Mathematics, Medium, Greedy algorithm
Problem

Kevin has n sticks. i-th stick has length ai.

Kevin wants every stick has the same length. To achieve his goal he can perform one of the following operation in one second:

  • Increase length of one stick by 1.
  • Reduce the length of one stick. If the stick has length L, the new length will be L2.

Your task is to help Kevin and say the minimum number of seconds to make all sticks have equal length.

Input format:

The first line of input will contain an integer t, denoting the number of test cases.
Each test case starts with the integer n. The next line contains n space-separated integers ai.

Output format:

For every test case output the minimum number of seconds Kevin need to achieve his goal.

Constraints:

  • 1t10
  • 1n1000,1ai1000 in 20% of the test cases.
  • 1n1000,1ai109 in 40% of the test cases.
  • 1n105,1ai109 in 40% of the test cases.
Time Limit: 7
Memory Limit: 256
Source Limit:
Explanation

Sequence of operations:
1) Break first stick. New length will be 3.
2) Increase length of the first stick. New length will be 4.
3) Increase length of the third stick. New length will be 4.
4) Break the last stick. New length will be 4.

Editor Image

?