Codeforces Round #287 (Div. 2) C. Guess Your Way Out! 二叉树遍历

思路:由样例可知,若exit和实际command在当前的父节点两边,则父节点一侧的子树节点必须全部遍历一遍,才会再次返回到父节点,从而转向正确的方向。

故先求出exit的正确路径,然后与command相比,

①若相同,则只需沿着command走,ans++

②若不相同,则ans += 父节点左侧子树的节点数

代码如下:

#include <cstdio>
using namespace std;
#define N 51
#define LEFT 0
#define RIGHT 1
long long fac[N], sum[N];
int dir[N];

int main(){
	int h;
	long long n;
	scanf("%d %I64d", &h, &n);
	fac[0] = 1, sum[0] = 1;
	for(int i = 1; i <= h; ++i)
		fac[i] = fac[i - 1] * 2, sum[i] = sum[i - 1] + fac[i];
	int level = h;
	long long ans = 0, cur = 0;
	int cmd = LEFT;
	for(int i = h; i > 0; --i){
        if(n > cur + fac[i - 1])
            dir[i] = RIGHT, cur += fac[i - 1];
	}
	while(level){
		if(cmd == dir[level]){
			++ans, --level;
		}
		else
			ans += sum[level - 1];
		cmd = 1 - cmd;
	}
	printf("%I64d\n", ans);
	return 0;
}


你可能感兴趣的:(二叉树,遍历,图论,codeforces)