题目链接:http://codeforces.com/problemset/problem/507/C
题目大意:
高度为h的满二叉树,从根节点出发,按照"LRLRLRLR...."的方式往下走,走到第n个叶子结点结束。如果走到了非n的叶子结点,那么就跳过下一个指令,回溯然后按照指令继续走没有走过的结点。问到达第n个叶子结点之前,有多少个结点被走过。
思路:
先设置一个初始方向。
高度一层一层减小,判断所走方向的子树包不包含叶子节点n。
如果不包含,那么可以知道那个方向的子树的所有结点都会走一遍的,于是直接把这个树的节点数加上就行然后往另外一个方向走!
如果包含,就往下走就行。
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
using namespace std ;
#define LL long long
LL n;
int h;
LL ans = 0, dir = 0;
int main()
{
scanf("%d%lld", &h, &n);
n--;
while(h--)
{
if(((n >> h) & 1) ^ dir) ans += (1LL << (h + 1));
else ans++, dir ^= 1;
}
cout << ans << endl;
return 0;
}