[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 }

 

posted @ 2017-08-18 20:29  Kirai  阅读(284)  评论(0编辑  收藏  举报