HDU 4260 The End of The World(漢羅塔)

來源:互聯網
上載者:User
  1. /* 很經典的規律題,應該要給以後
  2. 漢羅塔問題,要用到一個公式:假設N個盤子都在A上,那麼搬到B上則需要2^N - 1次。 
  3. dfs(B, pos)的作用是:將前面pos個盤子全部搬到B上所需要多少次。 
  4. 這樣,dfs(B, pos) = dfs(C, pos - 1) + pow(2.0, pos - 1) - 1 + 1; 
  5. 即,先將pos - 1個盤子都放在C處,然後將最後剩餘一個盤子放在B上,再將C上面的盤子都放回B處。 
  6. dfs中的B\C具體需要轉換 
  7. */  
  8.   
  9. #include <cstdio>
      
  10. #include <cstring>   
  11. #include <cmath>   
  12. const int nMax = 65;  
  13. char s[nMax];  
  14.   
  15. __int64 dfs(char B, int pos)  
  16. {  
  17.     if(pos == 0)  
  18.     {  
  19.         if(s[0] == B) return 0;  
  20.         else return 1;  
  21.     }  
  22.     else  
  23.     {  
  24.         if(s[pos] == B) return dfs(B, pos - 1);  
  25.         else  
  26.         {  
  27.             return (__int64)pow(2.0, pos) + dfs(3*'B' - B - s[pos], pos - 1);  
  28.         }  
  29.     }  
  30. }  
  31.   
  32. int main()  
  33. {  
  34.     while(gets(s))  
  35.     {  
  36.         if(s[0] == 'X') break;  
  37.         int len = strlen(s);  
  38.         __int64 ans = dfs('B', len - 1);  
  39.         printf("%I64d\n", ans);  
  40.     }  
  41.     return 0;  
  42. }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.