小猴子下落*

来源:互联网 发布:揭秘黑马程序员骗局 编辑:程序博客网 时间:2024/04/30 09:58

描述

有一颗二叉树,最大深度为D,且所有叶子的深度都相同。所有结点从左到右从上到下的编号为1,2,3,·····,2的D次方减1。在结点1处放一个小猴子,它会往下跑。每个内结点上都有一个开关,初始全部关闭,当每次有小猴子跑到一个开关上时,它的状态都会改变,当到达一个内结点时,如果开关关闭,小猴子往左走,否则往右走,直到走到叶子结点。

一些小猴子从结点1处开始往下跑,最后一个小猴儿会跑到哪里呢?

输入
输入二叉树叶子的深度D,和小猴子数目I,假设I不超过整棵树的叶子个数,D<=20.最终以 0 0 结尾
输出
输出第I个小猴子所在的叶子编号。
样例输入
4 23 40 0
样例输出
127

#include<cstdio>

#include<iostream>
#include<cstdlib>
#include<queue>
using namespace std;
struct tree{
bool status;
int num;
tree *left;
tree *right;
tree(){status=false;};
};


int D,N,count;
tree *root=new tree();


void buildTree(int depth,tree *root){
if(depth==20) return;

tree *NodeLeft=new tree();
root->left=NodeLeft;
buildTree(depth+1,NodeLeft);

tree *NodeRight=new tree();
root->right=NodeRight;
buildTree(depth+1,NodeRight);
}


queue<tree*>q;
void market(tree *root){
q.push(root);
tree *c;
while(!q.empty()){
c=q.front() ;
q.pop() ;
c->num=count++;
if(count==1048576) return;
q.push(c->left);
q.push(c->right); 
}
}


void reset(tree *root,int depth){
root->status=false;
if(depth==D) return;
reset(root->left,depth+1);
reset(root->right,depth+1);
}


int dfs(tree*root,int depth){
if(depth==D) return root->num;
if(root->status){
root->status=false;
dfs(root->right,depth+1);
}
else{
root->status =true;
dfs(root->left ,depth+1);
}
}


int main(){
count=1;
buildTree(1,root);
market(root);
while(scanf("%d %d",&D,&N),D!=0||N!=0){
while(--N) dfs(root,1);
printf("%d\n",dfs(root,1));
reset(root,1);
}
return 0;
}
原创粉丝点击