编程介的小学生 2019-09-09 21:57 采纳率: 20.5%
浏览 281

汉诺伊问题,Towers of Hanoi

Description

Surely you have already come across the Towers of Hanoi problem: Wooden disks of different sizes are stacked on three pegs, and initially, all disks are stacked on the same peg sorted by size, with the largest disk at the bottom. The objective is to transfer the entire tower to one of the other pegs, moving only one disk at a time and never putting a larger disk onto a smaller one.
According to an old myth, the monks at an ancient Tibetian monastery have been trying to solve an especially large instance of this problem with 47 disks for thousands of years. Since this requires at least 247 - 1 moves and the monks started out without a strategy, they messed it all up while still following the rules. Now they would like to have the disks stacked up neatly on any arbitrary peg using the minimum number of moves. But they all took a vow which forbids them to move the disks contrary to the rules. They want to know on which peg they should best stack the disks, and the minimum number of moves needed.
Write a program that solves this problem for the monks. Your program should also be able to handle any number N (0 < N <= 100 000) of disks. The numbers involved in the computation can become quite large. Because of that, the monks are only interested in the number of moves modulo 1 000 000.
Example
The following example can be solved in four moves.

Input

The first line of the input file hanoi.in consists of the number N (N <= 100000) of disks. The second line consists of three integers s1, s2, s3 with 0 <= s1, s2, s3 <= N and s1+s2+s3 = N, the number of disks on each of the three pegs. Lines three to five each contain the sizes of the disks for one peg. More precisely:
The (i + 2)-th line of the input file consists of integer numbers mi,1 . . .mi,si with 1 <= mi,j <= N, the sizes of the disks on peg i. The disks are given from bottom to top, thus mi,1 > mi,2 > . . . > mi,si .
Note that an empty stack is given by an empty line. The set of N disks have different sizes. All numbers are separated by a single space.
Output

The first line of the output file hanoi.out consists of the number d in {1, 2, 3} of the peg onto which the disks can be stacked using the minimum number of moves. The second line consists of the number M of required moves modulo 1 000 000.
Sample Input

7
2 1 4
2 1
3
7 6 5 4
Sample Output

3
4

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿