This page is still under construction.

Parts of this page are still being built. What you see may change.

Haybale Restacking

Interview

Time limit1sMemory limit128 MB

Summary
Given N piles in a circle with current and target amounts of hay, move bales at cost equal to circular distance to reach the target with minimum total work.
Level

Medium7 of 10

Topics
Greedy, Prefix sum, Math, Array
Solved
No attempts yet

Problem

Farmer John has just ordered a large number of hay bales. He wants to organize them into NN piles (1≤N≤100,0001 \le N \le 100{,}000) arranged in a circle, where pile ii should contain BiB_i bales of hay. Unfortunately, the delivery driver only remembered to leave the hay in NN piles arranged in a circle. After delivery, pile ii contains AiA_i bales of hay. Of course, the sum of the AiA_i equals the sum of the BiB_i.

Farmer John would like to move the bales from their current configuration (the AiA_i) into his target configuration (the BiB_i). Moving one bale from one pile to a pile that is xx steps away around the circle costs xx units of work. Compute the minimum total amount of work he needs.

Input

  • Line 1: the integer NN.
  • Lines 2 to N+1N+1: line i+1i+1 contains two integers AiA_i and BiB_i (1≤Ai,Bi≤10001 \le A_i, B_i \le 1000).

Output

Print a single integer: the minimum total units of work Farmer John needs.

Hint

In the first example there are 4 piles around a circle initially holding 7, 3, 9, and 1 bales, with target amounts 1, 4, 2, and 13. A minimum of 13 units of work suffices: move 6 bales from pile 1 to pile 4, move 1 bale from pile 3 to pile 2, and move 6 bales from pile 3 to pile 4. Because the piles form a circle, pile 1 and pile 4 are adjacent, so each of those moves costs just 1 step per bale.

Examples6

  1. Example 1

    Input
    4
    7 1
    3 4
    9 2
    1 13
    
    Expected output
    13
    
  2. Example 2

    Input
    1
    5 5
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    3 3
    4 4
    
    Expected output
    0
    
  4. Example 4

    Input
    2
    5 1
    1 5
    
    Expected output
    4
    
  5. Example 5

    Input
    3
    10 1
    1 1
    1 10
    
    Expected output
    9
    
  6. Example 6

    Input
    5
    4 2
    2 5
    6 1
    1 4
    2 3
    
    Expected output
    7