首页 > 代码库 > UVA10254 - The Priest Mathematician(找规律)

UVA10254 - The Priest Mathematician(找规律)

UVA10254 - The Priest Mathematician(找规律)

题目链接

题目大意:4根柱子的汉诺塔。

解题思路:题目里面有提示,先借助四个柱子移走k个,然后在借助三个柱子移走剩余的n - k个,再把n个移动到n - k个所在柱子。那么F[n] = min(2 * F[k] + H[n - k]);H[n - k] = 2^(n - k) - 1;把前面的60项打出来,再打印出F[n] - f[n - 1],会发现规律:
F[1] = 1;

F[2] = F[1] + 2^1;
F[3] = F[2] + 2^1;(2个)

f[4] = f[3] + 2^2;
f[5] = f[4] + 2^2;
f[6] = f[5] + 2^2;(3个)

F[7] = f[6] + 2^3;
... (4个)

但是n到达10000,结果要用到大数。

代码:

import java.util.*;
import java.math.*;
import java.io.*;

public class Main {

    static BigInteger f[] = new BigInteger[10005];
    public static void init () {

        f[0] = BigInteger.ZERO;
        f[1] = BigInteger.valueOf(1);
        int k = 1, j = 2;
        BigInteger addnum;

        while (j <= 10000) {
            addnum = BigInteger.valueOf(1).shiftLeft(k);
            for (int i = 0; i < k + 1 && j <= 10000; i++, j++) 
                f[j] = f[j - 1].add(addnum);
            k++;
        }    
    }

    public static void main(String args[]) {

        Scanner cin = new Scanner(System.in);
        init();

        while (cin.hasNext()) {

            int n = cin.nextInt();
            System.out.println(f[n]);
        }
    }
}

UVA10254 - The Priest Mathematician(找规律)