This page is still under construction.

Parts of this page are still being built. What you see may change.

Pattern Language

Time limit5sMemory limit512 MB

Summary
Each of M letters takes a digit up to its own limit u_i; count assignments that make the whole string a palindrome, where positions paired by mirror symmetry must get equal digits.
Level

Medium6 of 10

Topics
Union-find, Math, Combinatorics, Implementation
Solved
No attempts yet

Problem

There are MM distinct letters var1,var2,…,varMvar_1, var_2, \ldots, var_M. You are given a string s1s2s3…sNs_1s_2s_3\ldots s_N of length NN consisting of the 10+M10+M characters 0,1,…,9,var1,var2,…,varM0, 1, \ldots, 9, var_1, var_2, \ldots, var_M. You want to replace each letter in this string with a digit so that the result is a palindrome. (A palindrome reads the same forwards and backwards.) Equal letters must be replaced by equal digits. Every given letter varivar_i appears at least once in s1s2s3…sNs_1s_2s_3\ldots s_N.

Letter varivar_i can be replaced by an integer between 00 and uiu_i inclusive, without leading zeros. Count the number of replacement choices that make the resulting string a palindrome, modulo 109+710^9+7. Two choices are considered different if they assign different digits to any letter, even if the resulting string is the same.

Input

The input is given in the following format.

NN MM

s1s2s3…sNs_1s_2s_3\ldots s_N

var1var_1 u1u_1

......

varMvar_M uMu_M

Output

Print the number of replacement choices modulo 109+710^9 + 7 on one line.

Constraints

  • 1≤N≤5001 ≤ N ≤ 500
  • 1≤M≤101 ≤ M ≤ 10
  • 0≤ui≤990 ≤ u_i ≤ 99
  • sis_i ∈ {′0′,′1′,…,′9′,var1,var2,…,varM}\{'0', '1', \ldots, '9', var_1, var_2, \ldots, var_M\}
  • vari∈{′a′,′b′,…,′j′}var_i ∈ \{'a', 'b', \ldots, 'j'\}
  • Each letter varivar_i appears at least once in s1s2s3…sNs_1s_2s_3 \ldots s_N.
  • var1,var2,…,varMvar_1, var_2, \ldots, var_M are all distinct.

Examples3

  1. Example 1

    Input
    3 1
    a1a
    a 99
    
    Expected output
    19
    
  2. Example 2

    Input
    5 3
    jbfjb
    f 50
    b 25
    j 5
    
    Expected output
    252
    
  3. Example 3

    Input
    7 3
    jag2013
    j 53
    a 10
    g 93
    
    Expected output
    23