首页 > 其他 > 详细

汉诺塔模板

时间:2019-03-05 20:14:14      阅读:133      评论:0      收藏:0      [点我收藏+]

汉诺塔的模板

递归做法(超时):

#include <iostream>
#include <vector>
#include <stack>
using namespace std;
stack<int> S[3];
long long sum,hp;

void move(int A,int B){
    ++sum;
    int tmp = S[A].top();
    S[A].pop();
    hp += tmp;
    S[B].push(tmp);
}

void hanoi(int A,int B,int C,int n){
    if(n == 1){
        move(A,C);
        return;
    }else{
        hanoi(A,C,B,n-1);
        move(A,C);
        hanoi(B,A,C,n-1);        
    }
}

int main(){
    int n;
    cin >> n;
    for(int i=n;i>=1;--i){
        S[0].push(i);
    }
    hanoi(0,1,2,n);
    cout << sum << " " << hp << endl;
    return 0;
}

 

递推做法:

f[1] = 1;
f[n] = f[n-1] + 1 + f[n-1];
f[n] = (1LL << n) - 1;//大数避免pow 

 

汉诺塔模板

原文:https://www.cnblogs.com/--zz/p/10479188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!