题解:CF792D Paths in a Complete Binary Tree

· · 题解

思路

观察题目图片,我们很自然的想到了 \operatorname{lowbit},它表示一个数在二进制下最低位的 1 表示的值。

我们发现对于题目中的图,\operatorname{lowbit}(2) \times 2 = \operatorname{lowbit}(4), \operatorname{lowbit}(6) \times 2 = \operatorname{lowbit}(4),再多找几个点也符合,于是我们可以得出一个结论:\operatorname{lowbit}(u) \times 2 = \operatorname{lowbit}(fa_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;
}