#P3080. [USACO13MAR] The Cow Run G/S

[USACO13MAR] The Cow Run G/S

Description

Farmer John forgot to repair a hole in his fence, and his NN cows (1N10001 \le N \le 1000) escaped. Each minute a cow is outside the fence, she causes one dollar of damage. Farmer John must visit each cow to install a halter that calms the cow and stops the damage.

The cows are positioned at distinct locations along a straight road outside the farm. Farmer John knows the position PiP_i of each cow ii (relative to the gate at position 00 where he starts), with 500000Pi500000-500000 \le P_i \le 500000 and Pi0P_i \ne 0.

Farmer John moves at one unit of distance per minute, and installing a halter is instantaneous. Determine the order in which he should visit the cows to minimize the total damage, and compute the minimum total damage cost.

Input Format

  • Line 1: An integer NN, the number of cows.
  • Lines 2..N+12..N+1: Line i+1i+1 contains an integer PiP_i.

Output Format

  • Line 1: A single integer, the minimum total damage cost.
4 
-2 
-12 
3 
7 

50 

Hint

Four cows are at positions 2-2, 12-12, 33, and 77.

The optimal visit order is 2-2, 33, 77, 12-12. Farmer John arrives at position 2-2 in 22 minutes, causing 22 dollars of damage for that cow.

He then travels to position 33 (distance 55), where the cumulative damage for that cow is 2+5=72 + 5 = 7 dollars.

He spends 44 more minutes to get to 77 at a cost of 7+4=117 + 4 = 11 dollars for that cow.

Finally, he spends 1919 minutes to go to 12-12 with a cost of 11+19=3011 + 19 = 30 dollars.

The total damage is 2+7+11+30=502 + 7 + 11 + 30 = 50 dollars.

Translated by ChatGPT 5