Under construction

Still being built. Things may change

Game of Matchings

Time limit2sMemory limit512 MB

Summary
Count substrings of S that match pattern P under a bijective letter-to-number mapping, where distinct numbers must get distinct letters.
Level

Hard8 of 10

Topics
String matching, String, Hash map, Sliding window
Solved
No attempts yet

Problem

Adam and Carol are playing the game of matchings. The board is a string S=s1s2…s∣S∣S = s_1 s_2 \dots s_{|S|} of ∣S∣|S| lowercase English letters, and the goal is to find every place where a special kind of pattern PP matches inside SS. The pattern has length NN and is given by integers P1,P2,…,PNP_1, P_2, \dots, P_N between 1 and 26.

The contiguous substring sisi+1…si+N−1s_i s_{i+1} \dots s_{i+N-1} starting at position ii is a matching of PP when some mapping from the numbers of PP to lowercase letters meets both conditions: the mapping turns the pattern into sisi+1…si+N−1s_i s_{i+1} \dots s_{i+N-1}, and no two distinct numbers map to the same letter.

For example, if SS is awawww and PP is [10,21,10][10, 21, 10], the matchings are the two substrings of length three that start at positions 1 and 2, awa and waw. The substring www is not a matching, because the numbers 10 and 21 would both have to map to the letter w.

Adam and Carol lost the answer sheet and are not sure whether they found every matching. Given SS and PP, count the matchings.

Input

The first line contains the string SS. It is not empty, its length is at most 5×1055 \times 10^5, and every character is a lowercase letter from a to z.

The second line contains the pattern length NN (1≤N≤∣S∣1 \le N \le |S|).

The third line contains the NN integers P1,P2,…,PNP_1, P_2, \dots, P_N of the pattern, separated by spaces (1≤Pi≤261 \le P_i \le 26).

Output

Print one integer, the number of matchings of PP found in SS.

Examples4

  1. Example 1

    Input
    awawww
    3
    10 21 10
    
    Expected output
    2
    
  2. Example 2

    Input
    abcdefghij
    10
    1 2 3 4 5 6 7 8 9 1
    
    Expected output
    0
    
  3. Example 3

    Input
    abbabaabbaababba
    4
    1 2 2 1
    
    Expected output
    5
    
  4. Example 4

    Input
    aabcddabccefkkgem
    5
    10 10 3 14 9
    
    Expected output
    4