You are on page 1of 1

WallCraft (Hard Version)

Input file: standard input


Output file: standard output
Time limit: 1 second
Memory limit: 256 megabytes

The only difference between easy and hard version of the problem is the size of constraints.

Amazed by so many possibilities in Minecraft, you decided to build a fortress for yourself! You
started by building a wall of obsidian blocks. Overexcited, you built a wall of uneven height.
The wall is made up of consecutive pillars in a row. A pillar is made up of stacked up obsidian blocks.
The height of a pillar is the number of obsidian blocks it’s made up of. Let’s denote the i-th pillar from
left as pi . A wall can be described by an array h, where hi is the height of the pillar pi .
A wall of even height is made up of consecutive segment of pillars of same height and pillars
of zero height elsewhere. For example, [0, 0, 1, 0], [4, 4], [2, 2, 0, 0] are walls of even height whereas
[0, 0, 1, 0, 1], [1, 2, 0], [2, 3] are walls of uneven height.
To make the height of the wall even, you decide to use your precious diamond pickaxe to destroy some
obsidian blocks (possibly zero). For example, consider the array [1, 3, 3, 3, 4]. You can destroy one obsidian
block each from 1-st and 5-th pillars. The resulting array will be [0, 3, 3, 3, 3], which is a wall of even height.
Since diamonds are so rare in the game, you want to calculate the minimum number of obsidian blocks
to destroy.

Input
The first line of input contains a single integer T (1 ≤ T ≤ 105 )− the number of test cases.
The next 2T lines describe the test cases.
The first line of a test case contains one integer n (1 ≤ n ≤ 105 )− the length of the wall.
The second line of a test case contains n integers h1 , h2 , ..., hn (1 ≤ hi ≤ 109 ), where hi is the height of
i-th pillar pi .
Is is guaranteed that sum of n over all test cases does not exceed 105 .

Output
For each test case, output a single integer in a new line- the minimum number of obsidian blocks to
destroy to get a wall of even height.

Example
standard input standard output
2 2
5 0
1 3 3 3 4
3
5 5 5

Page 1 of 1

You might also like