UVa #437 The Tower of Babylon (例题9-2)

记忆化搜索,前两天看mit算法导论公开课里面Charles说这个memoization不算是动态规划,递推的才是。。


有机会的话回过头来写一些递推的


细节上,Rujia再一次给了这样的提示:如果数据范围太大但比较稀疏,则考虑给他们编码。在第五章的例题中(UVa 12096 The SetStack Computer(例题5-5),UVa 1592 Database(例题5-9))都有使用这种方法,是很常用也很重要的优化方法


Run Time: 0.016s

#define UVa  "LT9-2.437.cpp"		//The Tower of Babylon
char fileIn[30] = UVa, fileOut[30] = UVa;

#include
#include
#include

using namespace std;

struct Tower {
    int d[3][3];
    Tower(int a, int b, int c){
        d[0][0] = min(b, c); d[0][1] = max(b, c); d[0][2] = a;
        d[1][0] = min(a, c); d[1][1] = max(a, c); d[1][2] = b;
        d[2][0] = min(a, b); d[2][1] = max(a, b); d[2][2] = c;
    }
};

//Global Variables. Reset upon Each Case!
const int maxn = 30 + 10;
int n;
vector v;
int dp[maxn][3];
/////

int solve(int idx, int k) {
    if(dp[idx][k] >= 0) return dp[idx][k];
    dp[idx][k] = v[idx].d[k][2];
    for(int i = 0; i < n; i ++) {
        for(int j = 0; j < 3; j ++) {
            if(v[i].d[j][0] < v[idx].d[k][0] && v[i].d[j][1] < v[idx].d[k][1]) {
                dp[idx][k] = max(dp[idx][k], solve(i,j) + v[idx].d[k][2]);
            }
        }
    }
    return dp[idx][k];
}

int main() {
    int kase = 0;
    while(scanf("%d", &n) && n) {
        v.clear();
        int a, b, c;
        for(int i = 0; i < n; i ++) {
            scanf("%d%d%d", &a, &b, &c);
            v.push_back(Tower(a, b, c));
        }
        memset(dp, -1, sizeof(dp));
        int ans = -1;
        for(int i = 0; i < n; i ++) for(int j = 0; j < 3; j ++) ans = max(ans, solve(i,j));
        printf("Case %d: maximum height = %d\n", ++kase, ans);
    }
    return 0;
}

你可能感兴趣的:(第九章,-,动态规划初步,UVa,算法竞赛入门经典,ACM)