最长公共子序列,将1改为相应权值(即:每个长方体的高度值),其中注意给出的n个长方体,是长方体的种数,也就是说每种长方体可以有无数个。
代码如下:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; int step[3][3]={{0,1,2}, {0,2,1}, {1,2,0}}; int num, dp[100], tower[100][3]; int DP(int i) { if(dp[i] >= 0) return dp[i]; dp[i] = 0; for(int j=0; j<num; ++j) if( (tower[i][0]<tower[j][0]&&tower[i][1]<tower[j][1]) ||(tower[i][1]<tower[j][0]&&tower[i][0]<tower[j][1])) { dp[i] = max(dp[i], DP(j) + tower[j][2]); }437 - The Tower of Babylon return dp[i]; } int main() { #ifdef test freopen("input.txt", "r", stdin); #endif int cas = 0; while(scanf("%d", &num)) { if(num == 0) break; num *= 3; for(int i=0; i<num; i+=3) { scanf("%d%d%d", &tower[i][0], &tower[i][1], &tower[i][2]); for(int j=1; j<3; ++j)// 将一个长方体扩展成三个,每条边都做一次高 { tower[i+j][0] = tower[i][step[j][0]]; tower[i+j][1] = tower[i][step[j][1]]; tower[i+j][2] = tower[i][step[j][2]]; } } memset(dp, -1, sizeof(dp)); int _max = 0; for(int i=0; i<num; ++i) _max = max(_max, DP(i) + tower[i][2]); printf("Case %d: maximum height = %d\n", ++cas, _max); } return 0; }