猴子的下落

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   for   div   amp   

有一顆二叉樹,最大深度為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

根據完全二叉樹數組中的規律,

左子節點對父節點i的規律為:2i

右子節點對父節點i的規律為:2i+1

可以遞迴

 1 #include<iostream> 2 #include<math.h> 3 using namespace std; 4 int monkey(int i, int n, int c, bool tree[]) 5 { 6     if( c == n ) 7         return i; 8     if( !tree[i]) 9     {10         tree[i] = !tree[i];11         return monkey(2*i,n,++c,tree);12     }13     else14     {15         tree[i] = !tree[i];16         return monkey(2*i+1,n,++c,tree);17     }18 }19 20 int main()21 {22     int n,k,l;23     bool *tree = new bool[2048000];24     cin>>n>>k;25     while(n != 0 && k != 0)26     {27         for(int j=1; j <= pow(2,n+1)-1; j++)28             tree[j] = false;29         l = 1;30         while(l < k){31             monkey(1,n,1,tree);32             l++;33         }34         cout << monkey(1,n,1,tree)<<endl;35         cin>>n>>k;36     }37     return 0;38 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.