zoukankan      html  css  js  c++  java
  • HDU 2064 汉诺塔III (递推)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2064

    约19世纪末,在欧州的商店中出售一种智力玩具,在一块铜板上有三根杆,最左边的杆上自上而下、由小到大顺序串着由64个圆盘构成的塔。目的是将最左边杆上的盘全部移到右边的杆上,条件是一次只能移动一个盘,且不允许大盘放在小盘的上面。 
    现在我们改变游戏的玩法,不允许直接从最左(右)边移到最右(左)边(每次移动一定是移到中间杆或从中间移出),也不允许大盘放到下盘的上面。 
    Daisy已经做过原来的汉诺塔问题和汉诺塔II,但碰到这个问题时,她想了很久都不能解决,现在请你帮助她。现在有N个圆盘,她至少多少次移动才能把这些圆盘从最左边移到最右边? 

    Input包含多组数据,每次输入一个N值(1<=N=35)。Output对于每组数据,输出移动最小的次数。Sample Input

    1
    3
    12

    Sample Output

    2
    26
    531440

    题解:

    可知,要想把第n个盘从左(1)移到3,需要想把前n-1个从左(1)移动右(3),再从右(3)移到左(1),最后再从左(1)移到右(3)。
    而第n个盘要从左(1)到中(2)再右(3)经历2步。
    所以,f(n)=3*f(n-1)+1;经数学计算最终可得到f(n)=3^n-1;

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <cstring>
     4 #include <cstdio>
     5 #include <vector>
     6 #include <cstdlib>
     7 #include <iomanip>
     8 #include <cmath>
     9 #include <ctime>
    10 #include <map>
    11 #include <set>
    12 #include <queue>
    13 using namespace std;
    14 #define lowbit(x) (x&(-x))
    15 #define max(x,y) (x>y?x:y)
    16 #define min(x,y) (x<y?x:y)
    17 #define MAX 100000000000000000
    18 #define MOD 1000000007
    19 #define pi acos(-1.0)
    20 #define ei exp(1)
    21 #define PI 3.141592653589793238462
    22 #define INF 0x3f3f3f3f3f
    23 #define mem(a) (memset(a,0,sizeof(a)))
    24 typedef long long ll;
    25 ll gcd(ll a,ll b){
    26     return b?gcd(b,a%b):a;
    27 }
    28 bool cmp(int x,int y)
    29 {
    30     return x>y;
    31 }
    32 const int N=10005;
    33 const int mod=1e9+7;
    34 int main()
    35 {
    36     std::ios::sync_with_stdio(false);
    37     ll dp[36]={0,2};
    38     for(int i=2;i<36;i++){
    39         dp[i]=3*dp[i-1]+2;
    40     }
    41     int n;
    42     while(cin>>n){
    43         cout<<dp[n]<<endl;//dp[n]=3^n-1;
    44     }
    45     return 0;
    46 }
  • 相关阅读:
    分布式发布订阅消息系统 Kafka 架构设计[转]
    KAFKA分布式消息系统[转]
    文本协议与二进制协议的选择
    实现程序的热升级
    实现程序的热升级
    一个Socket数据处理模型
    关于GC进行垃圾回收的时机
    多线程
    线程同步(AutoResetEvent与ManualResetEvent)
    异步
  • 原文地址:https://www.cnblogs.com/wydxry/p/7297721.html
Copyright © 2011-2022 走看看