跳到正文

题解

题解:CF792D Paths in a Complete Binary Tree

nick_zha约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年6月25日
收录
2026年6月25日
更新
2026年11月9日
篇幅
约 3 分钟
题目
CF792D

版本

  1. v2当前
  2. v1

思路

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

我们发现对于题目中的图,lowbit⁡(2)×2=lowbit⁡(4),lowbit⁡(6)×2=lowbit⁡(4)\operatorname{lowbit}(2) \times 2 = \operatorname{lowbit}(4), \operatorname{lowbit}(6) \times 2 = \operatorname{lowbit}(4),再多找几个点也符合,于是我们可以得出一个结论:lowbit⁡(u)×2=lowbit⁡(fau)\operatorname{lowbit}(u) \times 2 = \operatorname{lowbit}(fa_u)(当且仅当 uu 存在父亲结点的时候)。

根据这个结论我们就可以做这个题了。

  • 对于 L 操作,u=u−lowbit⁡(u)2u = u - \frac{\operatorname{lowbit}(u)}2。
  • 对于 R 操作,u=u+lowbit⁡(u)2u = u + \frac{\operatorname{lowbit}(u)}2。
  • 对于 U 操作,u=u±lowbit⁡(u)u = u \pm \operatorname{lowbit}(u)。具体是加还是减取决于 uu 是左儿子还是右儿子。

AC Code

C++
#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;
}
原文