题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19499
题意:给一棵满二叉树,每个节点都有值:false或true。每次从顶点放球,走到一个节点,如果这个节点值为false,那么节点值变为true,且球就往左子树走,节点值为true,那么节点值变为false,且球往右子树走,直到走到某个叶子节点。问第i次放球时,会走到哪个叶子节点
思路:刚开始暴力模拟,果断TLE,然后仔细分析了一下,当p为偶数时,那么球应该往右子树走,为奇数时往左子树走,往下走d层即可
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int t, a, b;
while(scanf("%d", &t), t != -1)
{
for(int i = 0; i < t; i++)
{
scanf("%d%d", &a, &b);
int cnt = 1;
a--;
while(a)
{
if(b & 1) cnt *= 2; //往左子树走
else cnt = cnt * 2 + 1; //往右子树走
if(b & 1) b = b / 2 + 1; //往下走时,b若为奇数,则走到左子树的次数为b / 2 + 1
else b /= 2; //若为偶数,走到右子树的次数为b / 2
a--;
}
printf("%d\n", cnt);
}
}
return 0;
}