#P3051. [USACO12MAR] Haybale Restacking G

[USACO12MAR] Haybale Restacking G

Description

Farmer John has just ordered a large number of bales of hay. He would like to organize these into NN piles (1N100,0001 \le N \le 100{,}000) arranged in a circle, where pile ii contains BiB_i bales of hay. Unfortunately, the truck driver delivering the hay was not listening carefully when Farmer John provided this information, and only remembered to leave the hay in NN piles arranged in a circle. After delivery, Farmer John notes that pile ii contains AiA_i bales of hay. Of course, the AiA_i's and the BiB_i's have the same sum.

Farmer John would like to move the bales of hay from their current configuration (described by the AiA_i's) into his desired target configuration (described by the BiB_i's). It takes him xx units of work to move one hay bale from one pile to a pile that is xx steps away around the circle. Please help him compute the minimum amount of work he will need to spend.

Input Format

  • Line 11: The single integer NN.

  • Lines 21+N2\cdots1+N: Line i+1i+1 contains the two integers AiA_i and BiB_i (1Ai,Bi10001 \le A_i, B_i \le 1000).

4 
7 1 
3 4 
9 2 
1 13 

13 

Hint

There are 44 piles around a circle. Initially, the piles contain 77, 33, 99, and 11 bales of hay. Farmer John would like to move them so the piles contain 11, 44, 22, and 1313 bales of hay.

A minimum of 1313 units of work is required (move 66 bales from pile 11 to pile 44, move 11 bale from pile 33 to pile 22, and move 66 bales from pile 33 to pile 44).