Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out!
Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:
Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?
Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h).
Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.
1 2
2
2 3
5
3 6
10
10 1024
2046
A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one.
Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit.
题目大意:给出树的深度h,注意树是从0层开始算的,和最下面一层的第n个节点。问以LRLRLRLR。。。。的顺序走到那个节点的访问多少节点。
(PS:读成了整棵树的第n个节点,直接测试样例就过不去啊。。。。)
1、L走到节点的左子树。
2、R走到节点的右子树。
3、如果要到节点已经被访问过,跳过该步。
4、如果连续跳过两步,返回该节点的父节点。
5、如果到了非出口的叶子节点,返回该节点的父节点。
计算出从根到那个节点的路径。(LR的序列)
从L开始第一步,如果走的方向和路径相同,那么节点数+1,否则,就会走完那个子树的所有节点,然后向反方向走。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std ; #define LL __int64 LL num ; char s[100] , ch ; int main() { LL h , n , temp , i , j , ans ; while( scanf("%I64d %I64d", &h, &n) != EOF ) { temp = 1 ; for(i = 0 ; i < h ; i++) temp *= 2 ; temp-- ; temp += n ; n = temp ; h++ ; ans = 1 ; num = 0 ; temp = n ; while( temp > 1 ) { if( temp % 2 == 1 ) s[num++] = 'R' ; else s[num++] = 'L' ; temp /= 2 ; } s[num] = '\0' ; ch = 'L' ; for(i = num-1 ; i >= 0 ; i--) { if( ch == s[i] ) { ans++ ; if( ch == 'L' ) ch = 'R' ; else ch = 'L' ; } else { temp = 1 ; for(j = 0 ; j < h-(num-i) ; j++) temp *= 2 ; temp -= 1 ; ans += temp ; ans++ ; } } ans-- ; printf("%I64d\n", ans) ; } return 0; }