Rune Forest
Time limit3sMemory limit1024 MB
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 and bidirectional edges, and it forms a connected graph. Vertex has an uppercase English letter written on it. The bears build strings on the tree with the following rules.
- Start with an empty string .
- Choose vertices and . They may be the same vertex.
- Walk along the simple path (a path with no repeated vertices) that starts at and ends at . Append the letters on the visited vertices to the right end of , in the order they are visited. The letters on and are included.
The string built this way from and is written . The letters on the tree never disappear or change during the game.
Black Bear picks vertices and to build . White Bear picks vertices and to build . 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 .
From the second line, the next lines give the letter written on vertex on line . Each is an uppercase English letter.
From line , the next lines each contain the two endpoints and of an edge, separated by a space.
Line contains an integer .
From line , the next lines each contain four vertices separated by spaces, chosen by Black Bear and White Bear.
Output
Print lines. On line , print how many characters match when and are compared from the left end.