Under construction

Still being built. Things may change

Rune Forest

Time limit3sMemory limit1024 MB

Summary
Given a tree with a letter on each vertex, answer each query with the length of the longest common prefix of two path strings.
Level

Medium7 of 10

Topics
String matching, Tree, Binary search
Solved
No attempts yet

Problem

Black Bear and White Bear are a brother and sister pair of Komodo bears who live in Rune Forest. The two bears want to play a string game on a single tree in the forest. The tree in Rune Forest has vertices numbered 1 through NN and N−1N-1 bidirectional edges, and it forms a connected graph. Vertex ii has an uppercase English letter rir_i written on it. The bears build strings on the tree with the following rules.

  1. Start with an empty string SS.
  2. Choose vertices xx and yy. They may be the same vertex.
  3. Walk along the simple path (a path with no repeated vertices) that starts at xx and ends at yy. Append the letters on the visited vertices to the right end of SS, in the order they are visited. The letters on xx and yy are included.

The string built this way from xx and yy is written S(x,y)S(x,y). The letters on the tree never disappear or change during the game.

Black Bear picks vertices aa and bb to build S(a,b)S(a,b). White Bear picks vertices cc and dd to build S(c,d)S(c,d). Then they compare the two strings from the left end and count how many characters match. This is the Komodo bears' string game.

Input

The first line contains the number of vertices NN. (2≤N≤2×105)(2\leq N\leq 2\times 10^5)

From the second line, the next NN lines give the letter rir_i written on vertex ii on line i+1i+1. Each rir_i is an uppercase English letter.

From line N+2N+2, the next N−1N-1 lines each contain the two endpoints uiu_i and viv_i of an edge, separated by a space. (1≤ui<vi≤N)(1\leq u_i < v_i\leq N)

Line 2N+12N+1 contains an integer MM. (1≤M≤2×105)(1\leq M\leq 2\times 10^5)

From line 2N+22N+2, the next MM lines each contain four vertices ai,bi,ci,dia_i, b_i, c_i, d_i separated by spaces, chosen by Black Bear and White Bear. (1≤ai,bi,ci,di≤N)(1\leq a_i,b_i,c_i,d_i\leq N)

Output

Print MM lines. On line ii, print how many characters match when S(ai,bi)S(a_i,b_i) and S(ci,di)S(c_i,d_i) are compared from the left end.

Examples1

  1. Example 1

    Input
    5
    B
    B
    A
    C
    C
    1 2
    2 3
    2 4
    1 5
    5
    3 5 1 1
    1 2 2 5
    4 1 5 3
    5 3 3 5
    4 5 5 4
    
    Expected output
    0
    2
    3
    0
    4