【POJ 1958】 Strange Towers of Hanoi
【题目链接】
http://poj.org/problem?id=1958
【算法】
先考虑三个塔的情况,g[i]表示在三塔情况下的移动步数,则g[i] = g[i-1] * 2 + 1
再考虑四个塔的情况,f[i]表示在四塔情况下的移动步数,则f[i] = min{2*f[j]+g[i-j]}
【代码】
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; const int INF = 2e9; int i,j; int f[13],g[13]; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } int main() { g[1] = 1; for (i = 2; i <= 12; i++) g[i] = (g[i-1] << 1) + 1; f[1] = 1; for (i = 2; i <= 12; i++) { f[i] = INF; for (j = 1; j < i; j++) { f[i] = min(f[i],f[j]*2+g[i-j]); } } for (i = 1; i <= 12; i++) printf("%d\n",f[i]); return 0; }