动态规划练习 5

题目:Strange Towers of Hanoi (POJ 1958)

链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=1958

#include <iostream>
#include <limits.h>
 
using namespace std;
 
int main(int argc, char **argv)
{
    int h3[13], h4[13];
    
    h3[1] = 1;
    
    // Calculate all moves with i disks and 3 towers.
    for (int i = 2; i < 13; ++i)
    {
        h3[i] = 2 * h3[i - 1] + 1;
    }
    
    // Initialize min moves of i disks and 4 towers with INT_MAX.
    for (int i = 0; i < 13; ++i)
    {
        h4[i] = INT_MAX;
    }
    
    h4[1] = 1;
    
    // Output min moves of 1 disk and 4 towers.
    cout << h4[1] << endl;
    
    for (int i = 2; i < 13; ++i)
    {
        for (int k = 1; k < i; ++k)
        {
            const int h4i = 2 * h4[i - k] + h3[k];
            
            if (h4i < h4[i])
            {
                h4[i] = h4i;
            } 
        }
        
        // Output min moves of i (i >= 2 && i <= 12) disks and 4 towers.
        cout << h4[i] << endl;
    }
    
    return 0;
}
posted @ 2012-08-05 15:15  紫红的泪  阅读(249)  评论(1编辑  收藏  举报