Under construction

Still being built. Things may change

String Graph Matching

Interview

Time limit2sMemory limit1024 MB

Summary
Count the substrings of T whose set of adjacent letter pairs is exactly the given set of M directed edges.
Level

Medium5 of 10

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

Problem

You can build a graph from a string of lowercase letters as follows.

  1. Create a vertex for each lowercase letter from a to z.
  2. Write a string SS of length LL as S1S2S3⋯SLS_1S_2S_3\cdots S_L. For every positive integer ii with i≤L−1i \le L-1, add the edge Si→Si+1S_i \to S_{i+1} to the graph. If the same edge would be added more than once, add it only once.

Given a graph whose vertices are the lowercase letters and a string TT, count the substrings of TT that produce the same graph as the given graph through the process above.

A substring is a string of length at least 11 obtained by cutting some number of characters from the front and some number from the back of a string. For example, for abcde, cd and abc are substrings, but bd is not, because no amount of cutting from the front and back yields it.

Input

The first line contains an integer NN, the length of the string (2≤N≤2 000 0002 \le N \le 2\,000\,000).

The second line contains the string TT, which consists only of lowercase letters and has length NN.

The third line contains an integer MM, the number of edges in the graph (1≤M≤2621 \le M \le 26^2).

Each of the next MM lines contains two lowercase letters with no space between them. The line xiyix_iy_i denotes the directed edge xi→yix_i \to y_i. xix_i and yiy_i may be the same letter. No edge is given more than once.

Output

Print the number of substrings of TT that produce the same graph as the given graph through the process described above.

Examples2

  1. Example 1

    Input
    10
    raararaara
    3
    ra
    aa
    ar
    
    Expected output
    25
    
  2. Example 2

    Input
    10
    raararaara
    2
    ra
    ar
    
    Expected output
    7