UVA - 10795 A Different Task

本文介绍了一种特殊的汉诺塔问题,并提供了一段C++代码来解决该问题。通过对输入的不同盘子数量及初始状态进行分析,程序能够计算出将所有盘子从一个柱子移动到另一个柱子所需的最少步骤。

Input

The input le contains at most 100 test cases. Each test case starts with a positive integer N (1 ≤
N ≤ 60), which means the number of disks. You will be given the arrangements in next two lines. Each
arrangement will be represented by N integers, which are 1, 2 or 3. If the i-th (1 ≤ i ≤ N) integer is
1, you should consider that i-th disk is on Peg-A. Input is terminated by N = 0. This case should not
be processed.
Output
Output of each test case should consist of a line starting with `Case #: ' where # is the test case
number. It should be followed by the minimum number of moves as specied in the problem statement.
Sample Input
3
1 1 1
2 2 2
3
1 2 3
3 2 1
4
1 1 1 1
1 1 1 1
0
Sample Output
Case 1: 7
Case 2: 3
Case 3: 0

 

#include <cstdio>

using namespace std;

int A[70], B[70];

long long int f(int *A, int i, int x);

int main() {
    int n, t = -1;
    for (int base = 1; scanf("%d", &n) && n; t = -1) {
        for (int i = 0; i < n; ++i) {
            scanf("%d", A + i);
        }
        for (int i = 0; i < n; ++i) {
            scanf("%d", B + i);
            if (A[i] != B[i])
                t = i;
        }
        int x = 6 - A[t] - B[t];
        printf("Case %d: %lld\n", base++, t == -1 ? 0 : (f(A, t - 1, x) + f(B, t - 1, x) + 1));
    }
}

long long f(int *A, int i, int x) {
    if (i < 0)
        return 0;
    if (A[i] == x)
        return f(A, i - 1, x);
    return f(A, i - 1, 6 - x - A[i]) + (1LL << i);  //这里1LL要注意了
}

 

转载于:https://www.cnblogs.com/wangsong/p/7546213.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值