Under construction

Still being built. Things may change

Common Substring Queries

Time limit4sMemory limit1024 MB

Summary
Given N strings with total length up to 200,000, answer Q queries, each asking how many distinct substrings strings S_i and S_j share.
Level

Hard8 of 10

Topics
String matching, Tree, Sorting
Solved
No attempts yet

Problem

Given NN strings S1,…,SNS_1, \dots, S_N made only of lowercase English letters, write a program that processes the following query.

  • i ji\ j: Find the number of distinct common substrings of SiS_i and SjS_j.

A substring of a string is a non-empty contiguous part of that string. A common substring of two strings AA and BB is a string that is a substring of both AA and BB.

Input

The first line contains the number of strings NN (1≤N≤200 0001 \leq N \leq 200\,000). The next NN lines each contain one string S1,…,SNS_1, \dots, S_N made of lowercase letters, one per line. The total length of S1,…,SNS_1, \dots, S_N does not exceed 200 000200\,000.

The next line contains the number of queries QQ (1≤Q≤200 0001 \leq Q \leq 200\,000). The next QQ lines each contain two integers ii and jj (1≤i,j≤N1 \leq i, j \leq N).

Output

Print the answer to each of the QQ queries on its own line, in order.

Examples2

  1. Example 1

    Input
    5
    melon
    lemon
    apple
    grape
    peach
    5
    1 2
    4 5
    2 4
    3 4
    3 3
    
    Expected output
    6
    4
    1
    4
    14
    
  2. Example 2

    Input
    4
    sunrin
    high
    school
    olympiad
    5
    1 3
    2 2
    2 4
    3 2
    4 1
    
    Expected output
    1
    9
    1
    1
    1