uva 254(hanoi)

来源:互联网 发布:怎么样注销淘宝店铺 编辑:程序博客网 时间:2024/06/03 20:47

题意:汉诺塔问题,有三根柱子,第一个柱子上套n个圆盘,问走m步后每个柱子上有多少个圆盘。一般汉诺塔的目标状态是把盘子从第一根移到第三根柱子上,这题是如果n是奇数,目标状态是把盘子从第一根移到第二根柱子上。

题解:由于m可能取到2^100-1,用java的BIgnumber类会更好写,思路是先用一个数组hanoi表示最后每个柱子上会有多少个圆盘,a、b、c表示三根柱子初始是要将圆盘从a柱借助b柱移到c柱,初始值都为0,预处理ans[i]表示从第一根柱子上移走第i个圆盘需要的步数,也就是2^i-1,然后循环比较m与ans[i]的大小,如果m比较大,说明第i个圆盘会移动到第三个柱子上,所以hanoi[c]++,m去掉ans[i] - 1步,然后互换a、b的值,因为下一步是要将i - 1个圆盘从第二根柱子移到第三根柱子上;如果m比较小,说明第i个圆盘最后还在第一根柱子上,那么hanoi[a]++,互换b、c的值,因为下一步是要将i - 1个圆盘从a移到b,最后输出的时候根据题意如果n是奇数直接先输出hanoi[3]再输出hanoi[2]。

import java.math.BigInteger;import java.util.*;public class Main {    public static void main(String[] arge) {        int n;        int[] hanoi = new int[3];        BigInteger m = new BigInteger("0");        Scanner in = new Scanner(System.in);        BigInteger[] ans = new BigInteger[105];        BigInteger Two = new BigInteger("2");        BigInteger One = BigInteger.ONE;        BigInteger Zero = BigInteger.ZERO;        ans[1] = One;        ans[0] = Zero;        for (int i = 2; i < 105; i++)            ans[i] = ans[i - 1].multiply(Two).add(One);        while (true) {            n = in.nextInt();            m = in.nextBigInteger();            if (n == 0)                break;            for (int i = 0; i < 3; i++)                hanoi[i] = 0;            int a = 0, b = 1, c = 2;            for (int i = n - 1; i >= 0; i--) {                if (m.compareTo(ans[i]) <= 0) {                    hanoi[a]++;                    int temp = b;                    b = c;                    c = temp;                } else {                    hanoi[c]++;                    int temp = a;                    a = b;                    b = temp;                    m = m.subtract(ans[i]).subtract(One);                }            }            if (n % 2 == 0)                System.out.println(hanoi[0] + " " + hanoi[1] + " " + hanoi[2]);            else                System.out.println(hanoi[0] + " " + hanoi[2] + " " + hanoi[1]);        }    }}


0 0
原创粉丝点击