POJ 3601 Tower of Hanoi

Description
The Tower of Hanoi is a puzzle consisting of three pegs and a number of disks of different sizes which can slide onto any peg. The puzzle starts with the disks neatly stacked in order of size on one peg, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another peg, obeying the following rules:
•Only one disk may be moved at a time.
•Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg.
•No disk may be placed on top of a smaller disk.
For n disks, it is a well-known result that the optimal solution takes 2n − 1 moves.
To complicate the puzzle a little, we allow multiple disks to be of the same size. Moreover, equisized disks are mutually distinguishable. Their ordering at the beginning should be preserved at the end, though it may be disturbed during the process of solving the puzzle.
Given the number of disks of each size, compute the number of moves that the optimal solution takes.


【题目分析】
汉诺塔问题的变种,同样的汉诺塔会有多个,也没有什么不同,只需要分类dp一下就可以了。


【代码】

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int dp1[105],dp2[105], num[105];
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        for(int i=1;i<=n;i++) cin>>num[i];
        dp1[1]=num[1];
        for(int i=2;i<=n;i++) dp1[i]=(2*dp1[i-1]+num[i])%m;
        dp2[1]=2*(num[1]-1)+1;
        for(int i=2;i<=n;i++)
        {
            if(num[i]==1) dp2[i]=dp1[i]%m;
            else dp2[i]=(2*dp1[i-1]+2*num[i]+dp2[i-1])%m;
        }
        cout<<dp2[n]<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值