CF BUDDY
← Problems·

1990D · Grid Puzzle

1800 · bitmasks, brute force, dp

Problem: You are given an array aa of size nn.

There is an n×nn \times n grid. In the ii-th row, the first aia_i cells are black and the other cells are white. In other words, note (i,j)(i,j) as the cell in the ii-th row and jj-th column, cells (i,1),(i,2),,(i,ai)(i,1), (i,2), \ldots, (i,a_i) are black, and cells (i,ai+1),,(i,n)(i,a_i+1), \ldots, (i,n) are white.

You can do the following operations any number of times in any order:

  • Dye a 2×22 \times 2 subgrid white;
  • Dye a whole row white. Note you can not dye a whole column white.

Find the minimum number of operations to dye all cells white.

Input Format: The first line contains an integer tt (1t1041 \leq t \leq 10^4) — the number of test cases.

For each test case:

  • The first line contains an integer nn (1n21051 \leq n \leq 2 \cdot 10^5) — the size of the array aa.
  • The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (0ain0 \leq a_i \leq n).

It's guaranteed that the sum of nn over all test cases will not exceed 21052 \cdot 10^5.

Output Format: For each test case, output a single integer — the minimum number of operations to dye all cells white.

Note: In the first test case, you don't need to do any operation.

In the second test case, you can do:

  • Dye (1,1),(1,2),(2,1)(1,1), (1,2), (2,1), and (2,2)(2,2) white;
  • Dye (2,3),(2,4),(3,3)(2,3), (2,4), (3,3), and (3,4)(3,4) white;
  • Dye (3,1),(3,2),(4,1)(3,1), (3,2), (4,1), and (4,2)(4,2) white.

It can be proven 33 is the minimum number of operations.

In the third test case, you can do:

  • Dye the first row white;
  • Dye (2,1),(2,2),(3,1)(2,1), (2,2), (3,1), and (3,2)(3,2) white.

It can be proven 22 is the minimum number of operations.

Sample Cases

Case 1

Input

10
1
0
4
2 4 4 2
4
3 2 1 0
3
0 3 0
3
0 1 3
3
3 1 0
4
3 1 0 3
4
0 2 2 2
6
1 3 4 2 0 4
8
2 2 5 2 3 4 2 4

Output

0
3
2
1
2
2
3
2
4
6

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback