您的位置:首页 > 其它

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)。

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: