A recording studio's non-linear editor never stores a finished track as one long buffer of encoded samples. Instead it keeps the track as a binary splice tree: every node is either a leaf holding a short literal run of encoded samples (written as lowercase letters), or an internal splice node whose output is defined as "play everything the left child produces, then everything the right child produces." Given such a splice tree and a list of sample positions, determine — for each queried position — which character sits there in the fully assembled track, without ever having to splice the whole track together.
n, the number of nodes in the tree. Nodes are indexed 0 to n-1, and node 0 is the root.n lines describes node i (in index order) in one of two forms:
L s — a leaf whose literal snippet is the non-empty lowercase string s (no spaces).N l r — an internal splice node whose left and right children are nodes l and r (0 <= l, r < n).
It is guaranteed the nodes form a valid binary tree rooted at node 0: every node other than the root is the child of exactly one other node, leaves have no children, and internal nodes have exactly two children.q, the number of queries.q integers k_1 ... k_q, each a 1-indexed position into the fully assembled track (1 <= k_i <= the length of the track produced by the root).Print a single line containing the q answer characters concatenated together, one per query, in the order the queries were given.
Example 1
Input
5 N 1 2 L ab N 3 4 L cd L ef 3 1 4 6
Expected
adf
Explanation
Leaf node 1 holds 'ab', and leaf nodes 3 and 4 hold 'cd' and 'ef'. Node 2 (their parent) therefore produces 'cd'+'ef' = 'cdef', and the whole track (the root, node 0) produces 'ab'+'cdef' = 'abcdef'. Position 1 is 'a'. Position 4 falls past node 1's 2-character 'ab', so it becomes position 2 inside node 2's 'cdef', which is 'd'. Position 6 is the last character of 'abcdef', which is 'f'. Concatenating the three answers gives 'adf'.
Example 2
Input
1 L hello 2 1 5
Expected
ho
Explanation
The track is a single leaf holding 'hello'. Position 1 is its first character 'h', and position 5 is its last character 'o', giving the answer 'ho'.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →