1. 程式人生 > >Strange Towers of Hanoi (POJ1958)

Strange Towers of Hanoi (POJ1958)

oat 多少 space 最小 mat ins for int min

Strange Towers of Hanoi (POJ1958)

n個盤子4座塔的Hanoi問題至少需要多少步?(1<=n<=12)

分析:

n盤3塔: \(d[n] = 2*d[n-1]+1\) => \(d[n] = 2^n - 1\)

  1. 前n-1盤子 A -> B
  2. 第n盤子 A -> C
  3. 前n-1盤子 B -> C

n盤4塔:\(f[n] = min_{1\leq i<n}\{2*f[i] + d[n-i]\}\)

  1. 把i個盤子 A->B (四塔模式)
  2. 把n-i個盤子 A->D (三塔模式)
  3. 把i個盤子 B-> D (四塔模式)
  4. 考慮所有可能i取最小值

題解:

#include<iostream>
#include<cmath>

using namespace std;

int main(){
    int f[13] = {0};
    int minstep,step;

    f[1] = 1;
    for(int n=2;n<=12;n++){
        minstep = 0x3f3f3f3f;
        step=0;
        for(int i=1;i<n;i++){
            step = 2*f[i] + pow((float)2,n-i)-1;  //POJ C++的pow格式嚴格
            if(step<minstep)
                minstep = step;
        }
        f[n] = minstep;
    }

    for(int n=1;n<=12;n++){
        cout<<f[n]<<endl;
    }
    return 0;
}   

Strange Towers of Hanoi (POJ1958)