题意:
给你一棵完全二叉树, 要求从某个结点出发, 开始行走,可以向上走,向左走,向右走, 模拟这个过程。
思路:
观察那个二叉树的形状, 直接二分走就可以找到每一个结点。
我们先找到那个结点,然后从这个结点进行二分模拟行走, 因为有向上走的情况存在,所以可以开一个栈,来维护所走过的路。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
struct Node{
LL v;
LL L,R;
Node(LL v = 0,LL L = 0,LL R = 0):v(v),L(L),R(R){}
};
stack<Node>sk;
char s[maxn];
int main(){
LL n;
int q;
scanf("%lld %d",&n, &q);
while(q--){
LL m;
scanf("%lld%s",&m,s);
while(!sk.empty()) sk.pop();
LL l = 1, r = n;
LL cur = l+r>>1LL;
while(cur != m){
sk.push(Node(cur,l,r));
if (m < cur){
r = cur-1;
}
else l = cur + 1;
cur = l + r >> 1LL;
}
for (int i = 0; s[i]; ++i){
if (s[i] == 'U'){
if (sk.empty()) continue;
else {
cur = sk.top().v;
l = sk.top().L;
r = sk.top().R;
sk.pop();
}
}
else {
if (l == r) continue;
sk.push(Node(cur,l,r));
if (s[i] == 'L'){
r = cur-1;
}
else l = cur+1;
cur = l + r >> 1LL;
}
}
printf("%lld\n",cur);
}
return 0;
}