The researchers have n types of blocks, and an unlimited supply of blocks of each type. Each type-i block was a rectangular solid with linear dimensions (xi, yi, zi). A block could be reoriented so that any two of its three dimensions determined the dimensions of the base and the other dimension was the height.
They want to make sure that the tallest tower possible by stacking blocks can reach the roof. The problem is that, in building a tower, one block could only be placed on top of another block as long as the two base dimensions of the upper block were both strictly smaller than the corresponding base dimensions of the lower block because there has to be some space for the monkey to step on. This meant, for example, that blocks oriented to have equal-sized bases couldn't be stacked.
Your job is to write a program that determines the height of the tallest tower the monkey can build with a given set of blocks.
Input
representing the number of different blocks in the following data set. The maximum value for n is 30.
Each of the next n lines contains three integers representing the values xi, yi and zi.
Input is terminated by a value of zero (0) for n.
Output
For each test case, print one line containing the case number (they are numbered sequentially starting from 1) and the height of the tallest possible tower in the format "Case case: maximum height = height".
Sample Input1 10 20 30 2 6 8 10 5 5 5 7 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 5 31 41 59 26 53 58 97 93 23 84 62 64 33 83 27 0Sample Output
Case 1: maximum height = 40 Case 2: maximum height = 21 Case 3: maximum height = 28 Case 4: maximum height = 342
大致意思就是 给你n种无限个木块,问能用它们堆多高。堆叠的要求是上面木块的底要严格小于下面木块的底,也就是长和宽都不能相等。
首先是数据的处理,一块木块可以有六种摆放方式(详细见代码),因此干脆每种木块当六块读入,同时因为严格小于,痛同种木块不能堆叠因此不需要考虑重复。然后要把木块排个序,排成按长宽升序。
这道题还是很dp的,每一个木块能叠到多高取决于它上面叠的木块,当然它上面叠的木块高度也取决于它上面叠的木块。就……状态转移了。(大概吧)用dp[i]表示以木块i为底能叠多高。所以按长宽升序,因为长宽最小的木块上面是不能叠的,所以dp[0]就为第一块的高度。之后就是dp了,把i之前的dp数组遍历一下,找到最大的dp加上i的高就是dp[i]了。由于按长宽排序了,能保证叠最多层,同时dp[x]保证是用[x]为底的最大高度,所以叠出来的dp[i]也是最大高度,然后再一个遍历找出dp数组中的最大值就是最终答案了。
我局得这道题很好的体现了dp的思想。一个是需要保存状态,也就是目前堆叠的最大高度;一个是不记录具体决策,即我们不需要具体的摆放方式只需要高度即可;再一个就是全局最优解包含局部最优解,让每一个方块为底的情况都是能达到的最大高度,他们中的最大高度就是所要求得。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
struct cube
{
int l,w,h;
}cb[200];
int dp[200];
bool cmp(const cube a,const cube b)
{
if(a.l==b.l) return a.w<b.w;
return a.l<b.l;
}
int main()
{
int n,kase=0;
while(cin>>n&&n)
{
int t=0;
int a,b,c;
while(n--)
{
cin>>a>>b>>c;
cb[t].l=a;cb[t].w=b;cb[t++].h=c;
cb[t].l=a;cb[t].w=c;cb[t++].h=b;
cb[t].l=c;cb[t].w=a;cb[t++].h=b;
cb[t].l=c;cb[t].w=b;cb[t++].h=a;
cb[t].l=b;cb[t].w=a;cb[t++].h=c;
cb[t].l=b;cb[t].w=c;cb[t++].h=a;
}
sort(cb,cb+t,cmp);
dp[0]=cb[0].h;
int maxx;
for(int i=1;i<t;i++)
{
maxx=0;
for(int j=0;j<i;j++)
if(cb[i].l>cb[j].l&&cb[i].w>cb[j].w)
maxx=max(maxx,dp[j]);
dp[i]=cb[i].h+maxx;
}
maxx=0;
for(int i=0;i<t;i++)
maxx=max(maxx,dp[i]);
printf("Case %d: maximum height = %d\n",++kase,maxx);
}
return 0;
}