Strange Towers of Hanoi
作者:互联网
POJ
题意:求\(n(1<=n<=12)\)个盘子4座塔的\(Hanoi\)(汉诺塔)问题.
分析:设\(a[n]\)表示n盘3塔问题的答案,则\(a[n]=2*a[n-1]+1\).即把前n-1个盘子从A塔移动到B塔,然后把第n个盘子从A塔移动到C塔,最后把n-1个盘子从B塔移动到C塔.
设\(f[n]\)表示n盘4塔问题的答案,则\(f[n]=min_{1<=i<n}2*f[i]+a[n-i]\),即先把i个盘子在4塔模式下从A移动到B,然后把n-i个盘子在3塔模式下从A移动到D,最后把i个盘子在4塔模式下从B移动到D,其中取最小值.记得初始化\(f[1]=1\).
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
inline int read() {
int x=0,o=1;char ch=getchar();
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-')o=-1,ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*o;
}
int a[20],f[20];
int main() {
for(int n=1;n<=12;++n){
a[n]=2*a[n-1]+1;
f[n]=1e9;
}
f[1]=1;
for(int n=1;n<=12;++n)
for(int i=1;i<n;++i)
f[n]=min(f[n],2*f[i]+a[n-i]);
for(int n=1;n<=12;++n)printf("%d\n",f[n]);
return 0;
}
标签:ch,Towers,Hanoi,int,Strange,&&,盘子,include,getchar 来源: https://www.cnblogs.com/PPXppx/p/11222609.html