题目
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2511
题目来源:给新生的寒假训练1
简要题意:中文不表
题解
汉诺塔问题简介,了解的可以略去此部分
不妨假设要解决规模为n的汉诺塔问题,从from柱子以mid为中介放到to
有函数solve(int n, int from, int to, int mid)
于是我们可以先把1~n-1的碟子放到mid上:solve(n-1, from, mid, to);
然后我们把最下面的碟子放到to上
然后再把1~n-1从mid放到to上:solve(n-1, mid, to, from);
于是我们可以利用解决更小规模的相同问题来解决的这个问题,也就是递归。
只要将普通的汉诺塔稍加改造就能解决这个问题,只是要左右区间然后逼近结果。
汉诺塔问题分为三个阶段,可以比较容易看出,第一三阶段 lrcnt=2n−1−1 步,第二阶段 1 步。
可以看出来
m⩽lrcnt 时候在第一阶段,第二阶段就能直接知道结果,第三阶段是 m>lrcnt+1 。由于每一步必然是唯一一个汉诺塔子问题的第二阶段,因此只要在这里输出就行了。
光记录规模不够,要记录左右的边界,规模减下出来了。老问题散发新光芒,好题!
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef unsigned long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
inline LL getHanoi(int x) {
return (1ULL << x)-1;
}
void solve(int l, int r, LL m, int from, int to, int mid) {
LL lrcnt = getHanoi(r-l);
if (m <= lrcnt) {
solve(l, r-1, m, from, mid, to);
} else if (m == lrcnt+1) {
printf("%d %d %d\n", r, from, to);
} else {
solve(l, r-1, m-1-lrcnt, mid, to, from);
}
}
int main()
{
int n, t;
LL m;
scanf("%d", &t);
while (t--) {
scanf("%d%I64u", &n, &m);
solve(1, n, m, 1, 3, 2);
}
return 0;
}