Destroying Squares

Time limit5sMemory limit128 MB

Summary
Given an n x n matchstick grid (n <= 5) with some sticks already removed, find the minimum number of additional sticks to remove so that no square remains complete.
Level

Medium7 of 10

Topics
Backtracking, Bit manipulation, Brute force, Implementation
Solved
No attempts yet

Problem

Matchsticks are used to build an n×nn \times n grid. Every matchstick has length 1, and a complete n×nn \times n grid is made of 2n(n+1)2n(n+1) matchsticks. For example, a complete 3×33 \times 3 grid is made of 2×(3×4)=242 \times (3 \times 4) = 24 matchsticks.

The grid contains squares of various sizes. The size of a square equals the length of its side. A complete n×nn \times n grid contains (n−s+1)2(n-s+1)^2 squares of size ss. For example, a complete 3×33 \times 3 grid has 9 squares of size 1, 4 squares of size 2, and 1 square of size 3. A square "exists" when all of the matchsticks that form its perimeter are still present. (The matchsticks in its interior do not matter.)

Numbering the matchsticks. The matchsticks are numbered starting from 1, from left to right and from top to bottom. Concretely, the nn horizontal matchsticks of the top row are numbered from the left, and then the n+1n+1 vertical matchsticks directly below them are numbered from the left. This alternation of a horizontal line (nn matchsticks) and a vertical line (n+1n+1 matchsticks) continues downward, ending with the nn horizontal matchsticks of the bottom row. For example, in a complete 3×33 \times 3 grid, numbers 1-3 are the top horizontal matchsticks, 4-7 the vertical matchsticks below them, ..., and 22-24 the bottom horizontal matchsticks.

Removing some matchsticks from a complete grid destroys some squares, producing an incomplete grid. For example, removing matchsticks 12, 17, and 23 from a complete 3×33 \times 3 grid destroys 5 squares of size 1, 3 squares of size 2, and 1 square of size 3, leaving 4 squares of size 1 and 1 square of size 2.

You are given a complete or incomplete n×nn \times n grid built from at most 2n(n+1)2n(n+1) matchsticks (n≤5n \le 5). Write a program that finds the minimum number of matchsticks that must be removed to destroy every square remaining in the grid.

Input

The input consists of TT test cases. The first line contains the number of test cases TT. Each test case consists of two lines.

The first line contains the grid size nn (1≤n≤51 \le n \le 5). The second line first contains kk, the number of removed matchsticks, followed by the kk numbers of the removed matchsticks. If kk is 0 the grid is complete; otherwise it is incomplete.

Output

For each test case, output on its own line the minimum number of matchsticks that must be removed to destroy every square remaining in the given grid.

Examples1

  1. Example 1

    Input
    2
    2
    0
    3
    3 12 17 23
    
    Expected output
    3
    3