Under construction

Still being built. Things may change

What's the Order Anyway?

Interview

Time limit2sMemory limit1024 MB

Summary
Count the orderings of n comedy acts (n up to 10) that satisfy all given precedence and non-adjacency clues.
Level

Medium4 of 10

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

Statement

Alice, Bob, Carol, Denise, Eddie and Frank are performing in a local comedy show. Their stand-up routine order is not known. Instead, you have these cryptic clues (A is Alice, B is Bob, C is Carol, D is Denise, E is Eddie and F is Frank):

  • A > B
  • F < A
  • not C D

The first clue means that A performs before B. The second clue means that F performs after A. The third clue means that C and D do not perform consecutively. (If the acts are treated as numbers, the inequality signs assume the acts are sorted from greatest to least.)

Given these clues, one possible order is Alice, Carol, Bob, Denise, Frank, Eddie. The exact order may not be fixed by the clues, so the task is to count how many orders satisfy all of them.

Input

The first line contains two space-separated integers nn (2≤n≤102 \le n \le 10) and cc (1≤c≤101 \le c \le 10). Here nn is the number of comedy acts and cc is the number of clues. The acts are denoted by the first nn uppercase letters.

Each of the next cc lines contains a clue as three space-separated values aa, xx, and yy, where 1≤a≤31 \le a \le 3. The letters xx and yy are distinct uppercase letters among the first nn letters. The value aa gives the type of restriction:

  • a=1a = 1: the act of xx comes before the act of yy.
  • a=2a = 2: the act of xx comes after the act of yy.
  • a=3a = 3: the acts of xx and yy do not occur consecutively, in either order.

The clues are not contradictory, and at least one valid ordering exists.

Output

Print the number of different orders of the comedy acts that satisfy all the clues.

Examples2

  1. Example 1

    Input
    6 3
    1 A B
    2 F A
    3 C D
    
    Expected output
    160
    
  2. Example 2

    Input
    3 2
    1 C A
    2 B A
    
    Expected output
    1