KenKen You Do It?

Time limit2sMemory limit256 MB

Summary
Count the assignments of numbers 1 to n to the given cage cells that meet the target under the operator with distinct values in shared rows and columns.
Level

Medium5 of 10

Topics
Backtracking, Brute force
Solved
No attempts yet

Problem

KenKen is a logic puzzle that appeared in Japan in 2004. A puzzle is an n×nn \times n grid cut into sections that do not overlap, and each section carries an integer target together with one arithmetic operator. You fill the whole grid with numbers from 1 to nn so that both rules hold:

  • no number appears twice in the same row or in the same column
  • in every section the numbers of that section reach the target of the section under the operator of the section

This problem looks at a single section, not at a whole puzzle. The figure shows two sections taken from an 8×88 \times 8 puzzle, each with some of the ways its squares can be filled.

Two sections of an 8 by 8 KenKen puzzle with some of their fillings

The operator decides what the numbers of the section must satisfy:

  • +: the numbers add up to tt
  • *: the numbers multiply to tt
  • -: the section has exactly two squares, and the larger number minus the smaller one is tt
  • /: the section has exactly two squares, and the larger number divided by the smaller one is tt with no remainder

Squares outside the section do not matter. Two squares of the section that lie in the same row, or in the same column, still have to hold different numbers. Two fillings are different when some square holds a different number.

Placed in a 9×99 \times 9 puzzle, the first section of the figure gains two more fillings, the ones that use 9 and 2. In the first filling of the second section you cannot swap the 1 and the 4 of the top row, because that puts two 1s in the same column.

Input

The first line contains nn, mm, tt and op. Here nn is the size of the puzzle that holds the section, mm is the number of squares in the section, tt is the target value, and op is one of +, -, *, /.

After that come mm grid positions, each written as a row number rr and a column number cc. The positions take up one or more lines.

The squares of a section are connected: from any square of the section you reach every other square of the section by crossing shared edges between squares.

The values satisfy 4≤n≤94 \le n \le 9, 2≤m≤102 \le m \le 10, 0<t0 < t and 1≤r,c≤n1 \le r, c \le n.

Output

Print the number of ways the section can be filled in a KenKen puzzle of the given size.

Examples3

  1. Example 1

    Input
    8 2 7 -
    1 1 1 2
    
    Expected output
    2
    
  2. Example 2

    Input
    9 2 7 -
    1 1 1 2
    
    Expected output
    4
    
  3. Example 3

    Input
    8 3 6 +
    5 2 6 2 5 1
    
    Expected output
    7