#P15759. [JAG 2025 Summer Camp #1] Walking on Binary Tree

[JAG 2025 Summer Camp #1] Walking on Binary Tree

题目描述

You are given an infinite complete binary tree whose vertices are labeled with positive integers. The root is vertex 11, and for every vertex xx (x2x \geq 2), its parent is x2\left\lfloor \frac{x}{2} \right\rfloor.

You are also given a string S=S0S1SN1S = S_0 S_1 \ldots S_{N-1} of length NN. Each character of SS is either 'L' or 'R'.

Consider the following process: you are currently at some vertex uu, and want to reach vertex vv by repeatedly moving through the tree.

On the ii-th move (1-indexed), suppose you are at vertex xx. You may choose one of the following moves:

Downward move: If S(i1)modNS_{(i-1) \bmod N} is 'L', move to vertex 2x2x. Otherwise, move to vertex 2x+12x + 1.

Upward move: You can choose only if x2x \geq 2. Move to vertex x2\left\lfloor \frac{x}{2} \right\rfloor.

Note that you cannot stay at the same vertex.

You are given QQ independent queries. In the ii-th query, you start at vertex uiu_i and want to reach vertex viv_i.

For each query, determine whether it is possible to reach viv_i from uiu_i. If it is possible, find the minimum number of moves required.

输入格式

The input is given in the following format:

$$\begin{aligned} & N \\ & S \\ & Q \\ & u_1 \ v_1 \\ & u_2 \ v_2 \\ & \vdots \\ & u_Q \ v_Q \end{aligned}$$
  • 1N1061 \leq N \leq 10^6
  • 1Q200 0001 \leq Q \leq 200\ 000
  • 1ui,vi10181 \leq u_i, v_i \leq 10^{18} (1iQ1 \leq i \leq Q)
  • N,Q,uiN, Q, u_i and viv_i are integers.
  • SS is a string of length NN consisting of 'L' and 'R'.

输出格式

Output QQ lines. On the ii-th line, print the minimum number of moves required to reach viv_i from uiu_i if it is possible; otherwise, print "-1".

5
LLRLR
3
1 12
9 2
913 2025
7
2
23
1
L
1
1 3
-1