Under construction

Still being built. Things may change

LISA

Time limit3sMemory limit512 MB

Summary
Given n strings and range queries, count distinct concatenations of a non-empty prefix of one string in the range with a non-empty suffix of another string in the range.
Level

Hard9 of 10

Topics
Trie, String, Divide and conquer, Dynamic programming
Solved
No attempts yet

Problem

Ilya works at the Laboratory of Investigation of String Algorithms (LISA). He is trying to solve the following problem.

You are given an array of strings s1,s2,…,sns_1, s_2, \ldots, s_n and qq queries. Each query is given by two integers lil_i and rir_i (1≤li≤ri≤n1 \le l_i \le r_i \le n). To answer a query, consider the strings that can be built as follows. Choose two strings sxs_x and sys_y with li≤x,y≤ril_i \le x, y \le r_i. Take a non-empty prefix of sxs_x and a non-empty suffix of sys_y, and concatenate them. Call such a string representable. The answer to the query is the number of distinct representable strings for lil_i and rir_i.

For example, let s=[abc,ab,ac,bcac]s = [abc, ab, ac, bcac] and li=2l_i = 2, ri=3r_i = 3. The following strings are representable.

For x=2x = 2, y=2y = 2: ab = a + b, aab = a + ab, abb = ab + b, abab = ab + ab. For x=2x = 2, y=3y = 3: ac = a + c, aac = a + ac, abc = ab + c, abac = ab + ac. For x=3x = 3, y=2y = 2: ab = a + b, aab = a + ab, acb = ac + b, acab = ac + ab. For x=3x = 3, y=3y = 3: ac = a + c, aac = a + ac, acc = ac + c, acac = ac + ac.

So there are 12 distinct representable strings.

Input

The first line contains two integers nn and qq, the number of strings and the number of queries (1≤n,q≤1051 \le n, q \le 10^5). Each of the next nn lines contains a non-empty word sis_i made of lowercase English letters. The total length of all words does not exceed 10510^5. Each of the next qq lines contains two integers lil_i and rir_i (1≤li≤ri≤n1 \le l_i \le r_i \le n).

Output

Print qq lines. The ii-th line contains the answer to the ii-th query.

Examples1

  1. Example 1

    Input
    4 3
    abc
    ab
    ac
    bcac
    3 4
    1 3
    2 3
    
    Expected output
    20
    23
    12