Under construction

Still being built. Things may change

Favorite music

Time limit1sMemory limit256 MB

Summary
Given n note strings and q pairs, find the shortest string containing both given fragments as contiguous substrings, allowing overlap.
Level

Hard8 of 10

Topics
String matching, Trie, String, Implementation
Solved
No attempts yet

Problem

Al likes music a lot. He has nn favorite music fragments that he especially enjoys.

Music can be written down with notes. Here we ignore rests, note durations and octaves. There are no chords either, so two notes never sound at the same time. A music fragment is therefore a non-empty sequence of the following 12 note names.

C, C#, D, D#, E, F, F#, G, G#, A, A#, B

A fragment is written as its note names joined without spaces. A sharp note is written as a letter followed by #, and those two characters are a single note. For example, A#A is a fragment of the two notes A# and A, while AA# is a fragment of the notes A and A#.

The only thing better than listening to favorite music is listening to more favorite music. Al does not have much time for that, so he wants to know the smallest amount of time it takes to hear two fragments at once. The two fragments may overlap, but the notes of each fragment must sound in their original order, one right after another, with nothing inserted in between.

Each question gives the numbers of two fragments. Find the length of the shortest note sequence that contains both fragments this way. Hearing one note takes one unit of time.

Input

The first line contains the number of music fragments nn (1≤n≤3×1051 \le n \le 3 \times 10^5).

Each of the next nn lines contains one fragment, written as note names joined without spaces. All fragments are different. The sum of the lengths of the strings that describe the fragments is at most 3×1053 \times 10^5.

The next line contains the number of questions qq (1≤q≤1051 \le q \le 10^5).

Each of the next qq lines contains two different fragment numbers. Fragments are numbered from 11 to nn in the order they appear in the input.

Output

For each question, print on its own line the smallest amount of time needed to hear both fragments.

Examples2

  1. Example 1

    Input
    3
    ABCAB
    AC
    ACAB
    3
    1 2
    1 3
    2 3
    
    Expected output
    7
    7
    4
    
  2. Example 2

    Input
    5
    EBEBGF#DEEBEBF#GABBEBECBGAAADAEADA
    EECAGGECDECBAACDEECAAAFABCAGAAAA
    EECAGGECDECBAACDECEFGCGFEFDCDDDD
    G#A#CDD#FD#DCA#G#A#CDD#FDD#FGG#A#G#GFD#DD#FGG#A#
    GG#A#CDD#DCFD#DGFD#DCA#CDD#FGFD#A#CA#G#GFD#DCC
    3
    2 3
    4 5
    5 1
    
    Expected output
    64
    63
    66