Stacking Blocks
InterviewTime limit1sMemory limit128 MB
Reshape both towers into the V-shaped skyline with center height h at the lowest total cost of added and removed blocks.
- Level
Medium5 of 10
- Topics
- Sorting, Prefix sum, Math
- Solved
- No attempts yet
Problem
Yunhyeong and Donghyeok are playing with blocks. Each of them built one block building of width . Column of Yunhyeong's building holds blocks, and column of Donghyeok's building holds blocks. The two of them now want to stack and remove blocks until both buildings look exactly the same.

The new building has to take the pacman shape drawn on the right of the picture above. Going from left to right the number of blocks decreases and then increases, two neighboring columns differ by exactly one block, and the column with the fewest blocks sits at the exact center. Since is odd, let be the number of the center column. Column of a finished building then holds blocks for some integer .
To keep the room tidy, a block taken off a building goes straight into the block box. Moving a block to another spot means putting it into the box and then taking it back out to stack it. The box holds infinitely many blocks.
Stacking one block counts as one operation, and removing one block counts as one operation. Write a program that changes both buildings into the shape above with the smallest total number of operations.
Input
The first line contains the width of the two buildings. is odd.
The second line contains the column heights of Yunhyeong's building, , separated by spaces.
The third line contains the column heights of Donghyeok's building, , separated by spaces.
Output
Print the smallest total number of operations that stack or remove a block.
Constraints
Hint
In the first example, stack 2 more blocks on column 1 of Yunhyeong's building and 1 more block on column 3 of Donghyeok's building.