uva 1414(dp)

这是一篇关于UVA 1414题目的解析,主要探讨了带有特定序列操作的汉诺塔问题。文章指出,由于序列的固定,可以推导出圆盘移动的递推公式,并通过暴力计算f(2)、f(3)来确定递推系数,进而求解任意圆盘数目的移动步数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:汉诺塔问题,把A柱上n个圆盘全部移到B或C柱需要的步数,不同的是给出了一个序列,AB表示把A柱顶部的圆盘移到B柱顶上(按规则),这个序列每次从左到右扫描,找到可执行的第一个指令就执行一次,然后再从头扫描,同一个圆盘不能连续移动两次。问步数。
题解:看题解的,因为序列给出,移动的顺序就是固定的,可以推出来。在序列不变的情况下,随着圆盘数量的增加,移动次数线性增加(不会证明,手动笑哭),可以得到如下递推式
f(1) = 1
f(2) = x * f(1) + y
f(3) = x * f(2) + y
暴力求出f(2)、f(3)可以解出x、y,然后就可以递推求出f(n)。

#include <stdio.h>
#include <string.h>
#include <stack>
#include <algorithm>
using namespace std;
int n, s[6][6];
long long res;
char str[6];
stack<int> sta[3];

bool judge(int st, int en, int pre) {
    if (sta[st].empty())
        return false;
    if (sta[st].top() == pre)
        return false;
    if (sta[en].empty())
        return true;
    if (sta[st].top() < sta[en].top())
        return true;
    return false;
}

int solve(int x) {
    for (int i = 0; i < 3; i++)
        while (!sta[i].empty())
            sta[i].pop();
    for (int i = x; i > 0; i--)
        sta[0].push(i);
    long long temp = 0;
    int pre = -1;
    while (1) {
        if (sta[1].size() == x || sta[2].size() == x)
            return temp;
        for (int i = 0; i < 6; i++) {
            if (judge(s[i][0], s[i][1], pre)) {
                pre = sta[s[i][0]].top();
                sta[s[i][1]].push(pre);
                sta[s[i][0]].pop();
                temp++;
                break;
            }
        }
    }
}

int main() {
    while (scanf("%d", &n) == 1) {
        for (int i = 0; i < 6; i++) {
            scanf("%s", str);
            s[i][0] = str[0] - 'A';
            s[i][1] = str[1] - 'A';
        }
        int f2 = solve(2);
        int f3 = solve(3);
        int x = (f3 - f2) / (f2 - 1);
        int y = f3 - f2 * x;
        res = 1;
        for (int i = 2; i <= n; i++)
            res = res * x + y;
        printf("%lld\n", res);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值