This page is still under construction.

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

Open Sesame

Time limit1sMemory limit256 MB

Summary
Given pebble and groove heights per column, choose subarray moves adding or subtracting 1 each second to align all pebbles with grooves in minimum time.
Level

Medium7 of 10

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

Problem

Didi and chogahui05 followed a treasure map they picked up by chance and reached the spot it marked. The treasure was locked in a safe that opens only when a puzzle is solved. The puzzle goes like this.

There is a board of NN columns and 2312^{31} rows. Each of the NN columns holds one pebble and one groove that the pebble has to end up in.

Once per second you may choose XX consecutive columns and raise every pebble in them by one cell, or lower every pebble in them by one cell. A pebble that already sits in its groove can be moved too. The puzzle is solved and the safe opens once every pebble sits in a groove.

A pebble and a groove are both 1×11 \times 1, and a pebble counts as placed only when it sits exactly at the center of its groove. A pebble must never leave the board.

Didi wants to solve the puzzle as fast as possible while chogahui05 is away, then run off with the treasure. Write a program that computes the shortest time in seconds that solving the puzzle takes.

A board 3 columns wide and 5 rows tall

The picture above shows a board 3 columns wide and 5 rows tall, where ● is a pebble and ✕ is a groove. One of the fastest ways raises the pebbles in columns 1 to 3 by one cell, then lowers the pebble in column 2 twice. That takes 3 seconds.

Input

The first line contains the number of columns NN. (1≤N≤1,000,0001 \le N \le 1{,}000{,}000)

The second line contains NN integers separated by spaces, giving the positions of the pebbles. The iith number is the height YiY_i of the pebble in column ii. (0≤Yi<2310 \le Y_i < 2^{31})

The third line contains NN integers in the same format, giving the positions of the grooves. (0≤Yi<2310 \le Y_i < 2^{31})

Output

Print the shortest time in seconds that solving the puzzle takes.

Examples3

  1. Example 1

    Input
    3
    4 6 4
    5 5 5
    
    Expected output
    3
    
  2. Example 2

    Input
    1
    0
    0
    
    Expected output
    0
    
  3. Example 3

    Input
    5
    1 2 3 4 5
    5 4 3 2 1
    
    Expected output
    8