题解:CF792D Paths in a Complete Binary Tree
思路
观察题目图片,我们很自然的想到了
我们发现对于题目中的图,
根据这个结论我们就可以做这个题了。
- 对于
L操作,u = u - \frac{\operatorname{lowbit}(u)}2 。 - 对于
R操作,u = u + \frac{\operatorname{lowbit}(u)}2 。 - 对于
U操作,u = u \pm \operatorname{lowbit}(u) 。具体是加还是减取决于u 是左儿子还是右儿子。
AC Code
#include<bits/stdc++.h>
#define int long long
using namespace std;
int lowbit(int k) {return k & (-k);}
int _lg_(int k) {return 63 - __builtin_clzll(k);}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n, q;
cin >> n >> q;
while(q--){
int u;
string s;
cin >> u >> s;
for(auto v : s) {
if(v == 'U'){
if(u == (n + 1) / 2) continue;
else {
int lw = lowbit(u), pos = _lg_(lw);
if((u >> (pos + 1)) & 1) u -= lw;
else u += lw;
}
} else if(v == 'L') {
if(u & 1) continue;
int lw = lowbit(u);
u -= (lw >> 1);
} else {
if(u & 1) continue;
int lw = lowbit(u);
u += (lw >> 1);
}
}
cout << u << '\n';
}
return 0;
}