[CF792D] Paths in a Complete Binary Tree (规律, 位运算, lowbit)

Posted tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[CF792D] Paths in a Complete Binary Tree (规律, 位运算, lowbit)相关的知识,希望对你有一定的参考价值。

题目链接:http://codeforces.com/problemset/problem/792/D

 

画出树,找找规律,画图就好了。不算麻烦。

往下走的时候特判是不是叶子,往上走的时候特判是不是根。其余时候按照规律转移就是。

感觉可以推广到建树上,可以缩小常数是极好的。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long LL;
 5 LL lowbit(LL x) { return x & (-x); }
 6 const int maxn = 100010;
 7 LL n, u;
 8 int q;
 9 char s[maxn];
10 
11 signed main() {
12     // freopen("in", "r", stdin);
13     LL x, y, rt;
14     while(~scanf("%lld%d",&n,&q)) {
15         rt = 1;
16         while((1LL << rt) < n) rt++;
17         rt = 1LL << rt; rt >>= 1;
18         while(q--) {
19             scanf("%lld%s",&u,s);
20             bool ok = 1;
21             for(int i = 0; s[i]; i++) {
22                 x = u; y = lowbit(x);
23                 if(s[i] == L) {
24                     if(u & 1) continue;
25                     x ^= y; x |= (y >> 1);
26                     if(x >= 1) u = x;
27                 }
28                 else if(s[i] == R) {
29                     if(u & 1) continue;
30                     x |= (y >> 1);
31                     if(x <= n) u = x;
32                 }
33                 else {
34                     if(x == (x ^ y)) {
35                         if(u != rt) u = (x ^ y);
36                     }
37                     else {
38                         if(u != rt) u = (x ^ y) | (y << 1);
39                     }
40                 }
41             }
42             printf("%lld\n", u);
43         }
44     }
45     return 0;
46 }

 

以上是关于[CF792D] Paths in a Complete Binary Tree (规律, 位运算, lowbit)的主要内容,如果未能解决你的问题,请参考以下文章

D. Two Paths---cf14D

题解 CF1294F Three Paths on a Tree

CF 1000G Two-Paths (树形DP)

树的直径| CF#615Div3 F. Three Paths on a Tree

CF1000G Two-Paths

CF293B Distinct Paths