小猴子下落
時間限制:3000 ms | 內存限制:65535 KB
難度:3
- 描述
-
有一顆二叉樹,最大深度為D,且所有葉子的深度都相同。所有結點從左到右從上到下的編號為1,2,3,·····,2的D次方減1。在結點1處放一個小猴子,它會往下跑。每個內結點上都有一個開關,初始全部關閉,當每次有小猴子跑到一個開關上時,它的狀態都會改變,當到達一個內結點時,如果開關關閉,小猴子往左走,否則往右走,直到走到葉子結點。
一些小猴子從結點1處開始往下跑,最后一個小猴兒會跑到哪里呢?
- 輸入
- 輸入二叉樹葉子的深度D,和小猴子數目I,假設I不超過整棵樹的葉子個數,D<=20.最終以 0 0 結尾 輸出
- 輸出第I個小猴子所在的葉子編號。 樣例輸入
-
4 2 3 4 0 0
樣例輸出 -
12 7
超時代碼:
#include "stdio.h"
#include "string.h"
#define maxn 1<<20
bool tree[maxn+5];int main()
{int d,count;scanf("%d%d",&d,&count);do{int cur,max; //猴子的當前位置 ,節點的最大編號 memset(tree,0,sizeof(tree));//初始全部關閉for(int i=0;i<count;i++){cur=1; max=1<<d; while(2*cur<max){if(tree[cur]){ //向右走 tree[cur]=!tree[cur]; cur=cur*2+1; }else{ //向左走 tree[cur]=!tree[cur]; cur=cur*2; }}}printf("%d\n",cur); scanf("%d%d",&d,&count);}while(d!=0 || count!=0);return 0;
}
#include<stdio.h>
int main()
{int I,D; //猴子數、深度int res;while(scanf("%d%d",&D,&I)==2 && D>0 && I>0 ) {res=1;for(int i=0;i<D;i++){if(I%2==0){res=res*2+1;I=I/2;}else{res*=2;I=(I+1)/2;} }printf("%d\n",res/2); }return 0;
}
?????? 很多算法本身不是要模擬過程,模擬過程,必定的耗時耗內存,多尋找規律并不斷的優化。