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

[USACO13MAR] The Cow Run G/S

Problem Description

Farmer John has forgotten to repair a hole in the fence on his farm, and his NN cows (1N1,0001 \le N \le 1,000) have escaped and gone on a rampage! Each minute a cow is outside the fence, she causes one dollar worth of damage. FJ must visit each cow to install a halter that will calm the cow and stop the damage.

Fortunately, the cows are positioned at distinct locations along a straight line on a road outside the farm. FJ knows the location PiP_i of each cow ii (500,000Pi500,000-500,000 \le P_i \le 500,000, Pi0P_i \ne 0) relative to the gate (position 00) where FJ starts.

FJ moves at one unit of distance per minute and can install a halter instantly. Please determine the order that FJ should visit the cows so he can minimize the total cost of the damage; you should compute the minimum total damage cost in this case.

Input Format

  • Line 11: The number of cows, NN.
  • Lines 2N+12 \dots N+1: Line i+1i+1 contains the integer PiP_i.

Output Format

  • Line 11: The minimum total cost of the damage.
4 
-2 
-12 
3 
7 

50 

Hint

Four cows placed in positions: 2-2, 12-12, 33, and 77.

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

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

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.