# Paths in a Complete Binary Tree

## 题目描述

$T$ is a complete binary tree consisting of $n$ vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn’t have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So $n$ is a number such that $n+1$ is a power of $2$.
In the picture you can see a complete binary tree with $n=15$. Vertices are numbered from $1$ to $n$ in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.
You have to write a program that for given $n$ answers $q$ queries to the tree.
Each query consists of an integer number $u_i$ and a string $s_i$, where $u_i$ is the number of vertex, and $s_i$ represents the path starting from this vertex. String $s_i$ doesn’t contain any characters other than $L, R$ and $U$, which mean traverse to the left child, to the right child and to the parent, respectively. Characters from $s_i$ have to be processed from left to right, considering that $u_i$ is the vertex where the path starts. If it’s impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by $s_i$ ends.
For example, if $u_i=4$ and $s_i=UURL$, then the answer is $10$.

## 算法分析 $\because j$的右子树在$j$的右边，且在$i$的左边.
$\therefore (i-1)-j=s_j$.
$j=i-lowbit_j$.

$\therefore lowbit_i=2lowbit_j$.
$j=i-{lowbit_i \over 2}$.

$\because j$的左子树在$j$的左边，且在$i$的右边.
$\therefore (j-1)-i=s_j$.
$j=i+lowbit_j$.

$\therefore lowbit_i=2lowbit_j$.
$j=i+{lowbit_i \over 2}$.

①$i$在$j$左边.
$\because$等价于$L$操作的逆操作.
$\therefore i=j-lowbit_i$.
$j=i+lowbit_i$.
②$i$在$j$右边.
$\because$等价于$R$操作的逆操作.
$\therefore i=j+lowbit_i$.
$j=i-lowbit_i$.

## 代码

#include <iostream>
using namespace std;
long long n, t, p, len;
string s;
long long lowbit(long long t) {
return t & -t;
}
int main()
{
cin >> n >> t;
while (t--) {
cin >> p >> s;
len = s.length();
for (int i = 0; i < len; ++i) {
long long q = lowbit(p);
switch (s[i]) {
case 'U': {
if (p != n + 1 >> 1) {
p -= q;
p |= q << 1;
}
break;
}
case 'L': {
if (!(p & 1)) {
p -= q >> 1;
}
break;
}
case 'R': {
if (!(p & 1)) {
p += q >> 1;
}
break;
}
}
}
cout << p << endl;
}
return 0;
} 418 I'm a teapot