题解
【2025年科学月·线上选拔】汉诺塔
1 条题解
-
0
1. 解题思路
- 汉诺塔第 k 步移动的盘号是 k 的最低位 1 所在的位置。由于 k 用 n 位二进制给出,字符串最后一个 1 的位置就能直接确定盘号。
- 这个 1 前面的二进制前缀表示该盘已经完成的移动次数,对 3 取模即可确定当前所在柱子。
- 盘 d 的移动方向由 n-d 的奇偶性决定:偶数时按 A、C、B 方向循环,奇数时按 A、B、C 方向循环。
2. 坑点和注意事项
- k 可能有 100000 位,不能转成整数。
- 前导零不能影响最后一个 1 的位置;前缀只需维护模 3 的结果。
- 柱子编号用 A=0、B=1、C=2 表示,负方向取模后要加回 3。
3. 复杂度
时间复杂度: 每组 O(n);空间复杂度: O(1)。
/* 思路:最后一个 1 的位置决定盘号,前缀模 3 决定该盘的移动次数。 坑点:k 不能转整数;方向由 n 和盘号的奇偶性决定。 复杂度:每组 O(n),空间 O(1)。 */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int q; cin >> q; while (q--) { int n; string s; cin >> n >> s; int pos = (int)s.rfind('1'); int disk = n - pos; int turn = 0; for (int i = 0; i < pos; i++) { turn = (turn * 2 + s[i] - '0') % 3; } int dir = ((n - disk) % 2 == 0 ? -1 : 1); int from = (turn * dir % 3 + 3) % 3; int to = (from + dir + 3) % 3; const char name[3] = {'A', 'B', 'C'}; cout << disk << ' ' << name[from] << ' ' << name[to] << endl; } return 0; }
- 1