hdu 2511 汉诺塔 X 递归 构造
来源:互联网 发布:网络销售客户不说话 编辑:程序博客网 时间:2024/05/16 19:04
题目
题目链接: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 secondusing 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;}// headinline 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;}
0 0
- hdu 2511 汉诺塔 X 递归 构造
- hdu 2511 汉诺塔X
- hdu 2511 汉诺塔 X
- hdu 4850 字符串构造---欧拉回路构造序列 递归+非递归实现
- hdu 1997 汉诺塔VII(递归)
- HDU 1997 汉诺塔VII(递归)
- HDU 2064 汉诺塔III (递归)
- 递归构造树 treeview
- 递归构造json字符串
- 构造器递归调用
- 递归构造格雷码
- HDU 1997、2184、2175、2511 汉诺塔VII、VIII、IX、X
- HDU 2511 汉诺塔X(递推+DFS)
- HDU:1997 汉诺塔VII(规律||递归)
- 个人笔记-递归构造树
- hdu 3306 矩阵构造
- HDU 3306 矩阵构造
- hdu 3483 矩阵构造
- eclipse代码自动补全
- TortoiseSVN中的“文件和文件夹过滤”在VS项目中的使用
- 网络服务器开发总结
- Android平台下hook框架adbi的研究(上)
- 自定义View的成长之路
- hdu 2511 汉诺塔 X 递归 构造
- Android平台下hook框架adbi的研究(下)
- 93. Spiral Matrix
- leetcode166. Fraction to Recurring Decimal
- Good Bye 2015 D. New Year and Ancient Prophecy
- 常用正则表达式
- Java异常:选择Checked Exception还是Unchecked Exception?
- 蓝桥杯:基础练习 杨辉三角形
- PHP命名空间 namespace 和 自动加载