Prefix Suffix Search

Time limit3sMemory limit512 MB

Summary
Given N words and Q prefix/suffix pairs, report for each query how many words match both prefix and suffix. Total input length is up to 2.5 million.
Level

Hard8 of 10

Topics
String matching, Trie, Hash map, Divide and conquer
Solved
No attempts yet

Problem

As an English learner, sometimes you cannot remember the entire spelling of an English word perfectly, and you can only remember its prefix and suffix. For example, you may want to use a word that begins with appr and ends with iate, but forget the middle part. It may be appreciate, appropriate, or something like them.

With an ordinary dictionary you can look up words beginning with a certain prefix, but filtering words that end with a certain suffix as well is inconvenient. So dictionary functionality that finds words having a given prefix and suffix is helpful. To start, let us count the number of such words instead of listing them all.

More formally, you are given a list of NN words. Then you are given QQ queries, each consisting of two strings. Write a program that outputs, for each query, the number of words in the given list that have both the given prefix and the given suffix.

Input

The input consists of a single test case in the following format.

$N$ $Q$
$w_1$
...
$w_N$
$p_1$ $s_1$
...
$p_Q$ $s_Q$

The first line contains two integers NN and QQ, where NN (1≤N≤1051 \le N \le 10^5) is the number of words in the list and QQ (1≤Q≤1051 \le Q \le 10^5) is the number of queries. The ii-th of the following NN lines contains a string w_iw\_i. The ii-th of the following QQ lines contains two strings p_ip\_i and s_is\_i, which are the prefix and suffix of the words to be searched for.

You can assume the following.

  • All strings in the input are non-empty and consist only of lowercase English letters.
  • The total length of the input strings does not exceed 2,500,0002{,}500{,}000.
  • The words in the given list are unique: w_i≠w_jw\_i \neq w\_j if i≠ji \neq j.
  • The pairs of a prefix and a suffix are unique: (p_i,s_i)≠(p_j,s_j)(p\_i, s\_i) \neq (p\_j, s\_j) if i≠ji \neq j.

Output

For each query, output the number of words in the given list that have the given prefix and suffix, one per line.

Examples3

  1. Example 1

    Input
    6 7
    appreciate
    appropriate
    acceptance
    ace
    acm
    acetylene
    appr iate
    a e
    a a
    ac ce
    ace e
    acceptance acceptance
    no match
    
    Expected output
    2
    5
    0
    2
    2
    1
    0
    
  2. Example 2

    Input
    5 5
    d
    dd
    ddd
    dddd
    ddddd
    d d
    dd dd
    ddd ddd
    d dddd
    ddddd dd
    
    Expected output
    5
    4
    3
    2
    1
    
  3. Example 3

    Input
    7 4
    connected
    disconnected
    graph
    directed
    diameter
    distance
    minor
    c ed
    di ed
    dis ed
    dis e
    
    Expected output
    1
    2
    1
    1