uva 1414(dp)
2015-07-25 14:54
351 查看
题意:汉诺塔问题,把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)。
题解:看题解的,因为序列给出,移动的顺序就是固定的,可以推出来。在序列不变的情况下,随着圆盘数量的增加,移动次数线性增加(不会证明,手动笑哭),可以得到如下递推式
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; }
相关文章推荐
- jquery autocomplete前后台整合实例(1)
- django 1.8 官方文档翻译: 2-6-2 遗留的数据库
- Html5标签查缺补漏
- sqlserver几个好用的表值函数和标量函数
- 数据结构——Currency System in Geraldion
- 【转】wireshark过滤规则
- iOS- 利用AFNetworking(AFN) - 实现文件断点下载
- Majority Element浅谈 (A linear time iceberg query algorithm)
- hdu 4417
- HBuilder动态的向<ul></ul>中插入<li></li>
- uwsgi 问题总结
- kiki's game
- hdu5304 基环 外向树
- 正则表达式校验车牌号
- HDU 1302 The Snail
- 用UltraEdit比较两个文件
- linux 可以ping本机 无法连接SecureCRT
- 数据结构基础温故-5.图(上):图的基本概念
- VIM使用(二) 浏览内核源代码
- LeetCode -- 求字符串数组中的最长公共前缀