汉诺塔问题,本来以为是个递推公式的题,f[n] = 2*f[n-2] + 3;后来发现当计算到 f[12]的时候就出错了,搜解题报告后发现原来是个动归的题
其中需要用double 类型来存储数据,
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
double a[65];
double f[65];
int main() {
int n;
memset(a, 0, sizeof(a));
memset(f, 0, sizeof(f));
a[1] = 2;
f[1] = 1;
for(int i = 2; i < 65; i++) {
a[i] = a[i-1] * 2;
}
for(int i = 2; i < 65; i++) {
double tmp;
double mmin = a[i] - 1;
for(int j = 1; j < i; j++) {
tmp = a[i-j] - 1 + 2 * f[j];
if(tmp < mmin) {
mmin = tmp;
}
}
f[i] = mmin;
}
while(scanf("%d", &n) != EOF) {
printf("%.0lf\n", f[n]);
}
return 0;
}