Lock Pattern
Time limit5sMemory limit128 MB
Count valid lock patterns on a 3 by 4 grid whose Manhattan segment lengths sum to L while avoiding the dots in S.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Bit manipulation
- Solved
- No attempts yet
Problem
The most common way to lock a phone is a lock pattern. To unlock it you connect the dots on the screen in the right order so that they draw a fixed shape.
Cheongho's phone uses a lock pattern with 4 rows of 3 dots each. The board is modelled as a 2D plane, and every dot is an integer lattice point . The top left dot is and the bottom right dot is , so grows from 1 to 3 going right and grows from 1 to 4 going up.
A valid pattern is defined as follows.
- A pattern is the sequence of dot coordinates written down at the moment each dot is first passed, in drawing order. Because the drawing order differs, and are two different patterns.
- For any two consecutive dots and in the pattern, every other dot lying on the segment must already appear earlier in the pattern. For example is not a valid pattern, while and are valid.
- A pattern may pass the same dot more than once, but no dot may be written down more than once. Each dot counts as a dot of the pattern only the first time it is passed.
- The length of a pattern is the sum of the Manhattan distances between consecutive dots. The Manhattan distance between and is .
- A pattern has to contain at least two dots.
For example, is a valid pattern over eight dots.
One day Cheongho forgot the lock pattern of his phone. He still remembers the length of the pattern and the set of dots the pattern never passed. A dot outside may or may not have been passed.
Cheongho wants to try every remaining case one by one. Before that he wants to count how many tries that will take. Given and , how many different valid patterns are there?
Input
The first line has the number of test cases . ()
The first line of each test case has and . is the length of the pattern and is the number of dots Cheongho remembers as never passed. (, )
Each of the next lines has two integers and . (, ) This means the pattern never passed the dot .
The dots are all different.
Output
For each test case, print the number of possible valid patterns on its own line.
If no pattern is possible at all, print BAD MEMORY instead of a number.