小猴子下落
時間限制:3000 ms | 內存限制:65535 KB
難度:3
輸入
輸入二叉樹葉子的深度D,和小猴子數目I,假設I不超過整棵樹的葉子個數,D<=20.最終以 0 0 結尾
輸出
輸出第I個小猴子所在的葉子編號。
樣例輸入
4 2
3 4
0 0
樣例輸出
12
7
描述
有一顆二叉樹,最大深度爲D,且所有葉子的深度都相同。所有結點從左到右從上到下的編號爲1,2,3,·····,2的D次方減1。在結點1處放一個小猴子,它會往下跑。每個內結點上都有一個開關,初始全部關閉,當每次有小猴子跑到一個開關上時,它的狀態都會改變,當到達一個內結點時,如果開關關閉,小猴子往左走,否則往右走,直到走到葉子結點。
一些小猴子從結點1處開始往下跑,最後一個小猴兒會跑到哪裏呢?
這到題既可以用樹來暴力,最好的解法是可以找到數學的規律,我就是想寫個樹來練練,好久沒寫馬上快不會寫了。。。我參考了大神的,詳情移步大神博客https://www.cnblogs.com/ljwTiey/p/4295704.html
/*
1、創建節點,節點上立flag來記錄開關正負
2、創建d高的樹,並且爲每個葉子編號
3、遍歷整個數,並且每走過樹,將開關逆轉
4、遍歷num次 ,最後記錄第t個小猴子的節點
*/
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
typedef struct node{
int flag;
int date;
node *rchild, *lchild;
node();
}node,*Lnode;
node::node(){
flag=-1;
rchild=NULL;
lchild=NULL;
}
void createTree(int d,Lnode &root)
{
queue<node *> que;
static int count=0;
root=new node;
root->date=++count;
que.push(root);
node *t=root;
while(count!=pow(2,d)-1)
{
t=que.front();
que.pop();
t->lchild=new node;
t->lchild->date=++count;
que.push(t->lchild);
t->rchild=new node;
t->rchild->date=++count;
que.push(t->rchild);
}
t=NULL;
count=0;
}
void run(int &t,Lnode &root)
{
if(root->lchild!=NULL && root->rchild!=NULL)
{
if(root->flag==-1)
{
root->flag=1;
run(t,root->lchild);
}
else
{
root->flag=-1;
run(t,root->rchild);
}
}
else
t=root->date;
}
int main()
{
int a,b;
while(cin>>a>>b,a&&b)
{
node *root=new node;
createTree(a,root);
int t;
for(int i=0;i<b;i++)
{
run(t,root);
}
cout<<t<<endl;
}
return 0;
}
根據猴子走四層的樹,看看猴子到達的位置
第1只猴子 | 1 | 2 | 4 | 8 |
第2只猴子 | 1 | 3 | 6 | 12 |
第3只猴子 | 1 | 2 | 5 | 10 |
第4只猴子 | 1 | 3 | 7 | 14 |
第5只猴子 | 1 | 2 | 4 | 9 |
第6只猴子 | 1 | 3 | 6 | 13 |
第7只猴子 | 1 | 2 | 5 | 11 |
第8只猴子 | 1 | 3 | 7 | 15 |
通過觀察,當第i只猴子i爲奇數時,下一個節點的號是k=k*2,i改變爲i=(i+1)/2,並且進入左子樹
當第i只猴子i爲偶數時,下一個節點的號是k=k*2+1,i改變爲i=i/2,並且進入右子樹
因此,第i個猴子所到的節點爲k,這裏關鍵代碼是(high是樹高,小猴子共跳了high-1次)
for (int j=0;j<high-1;j++)
{
if(i%2)
{k=k*2;i=(i+1)/2;}
else
{k=k*2+1;i /=2;}
}