1. 程式人生 > >[CF792D] Paths in a Complete Binary Tree (規律, 位運算, lowbit)

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

規律 set turn freopen pre names main () 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)