Destroying Squares
Time limit5sMemory limit128 MB
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 grid. Every matchstick has length 1, and a complete grid is made of matchsticks. For example, a complete grid is made of matchsticks.
The grid contains squares of various sizes. The size of a square equals the length of its side. A complete grid contains squares of size . For example, a complete 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 horizontal matchsticks of the top row are numbered from the left, and then the vertical matchsticks directly below them are numbered from the left. This alternation of a horizontal line ( matchsticks) and a vertical line ( matchsticks) continues downward, ending with the horizontal matchsticks of the bottom row. For example, in a complete 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 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 grid built from at most matchsticks (). 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 test cases. The first line contains the number of test cases . Each test case consists of two lines.
The first line contains the grid size (). The second line first contains , the number of removed matchsticks, followed by the numbers of the removed matchsticks. If 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.