[poj 3601]Tower of Hanoi 数论

http://poj.org/problem?id=3601

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.

Input

The input contains multiple test cases. Each test case consists of two lines. The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 106). The second lines contains n integers a1a2, …, an (1 ≤ a1a2, …, an ≤ 105). For each 1 ≤ i ≤ n, there are ai disks of size i. The input ends where EOF is met.

Output

For each test case, print the answer modulo m on a separate line.

Sample Input

1 1000
2
5 1000
1 1 1 1 1
5 1000
2 2 2 2 2
5 1000
1 2 1 2 1

Sample Output

3
31
123
41

Source


拿到这道题刚开始的想法是推出了A[i]的递推式子。


但是题目的要求是从上到下应该是保序的。

最后发现这个是具体数学上的一道原题。

公式为

B[i=2*c[i]-1;(i=1)

B[i]=2*a[i-1]+2*c[i]+b[i-1]; (i>1 且 c[i]>1)

B[i]=a[i];(c[i]=1)

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <ctype.h>
using namespace std;
int n,m,i;
int a[105],b[105],c[105];
int main()
{
    while (scanf("%d %d",&n,&m)!=EOF)
    {
	for (i=1;i<=n;i++)
		scanf("%d",&c[i]);
	memset(b,0,sizeof(b));
	memset(a,0,sizeof(a));
	for (i=1;i<=n;i++)
		a[i]=(a[i-1]*2+c[i])%m;
	b[1]=(2*c[1]-1)%m;
	for (i=2;i<=n;i++)
		if (c[i]==1) b[i]=a[i];
		else b[i]=(2*a[i-1]+2*c[i]+b[i-1])%m; 
	printf("%d\n",b[n]);
	}
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值