HDU 1069 Monkey and Banana dp 题解

HDU 1069 Monkey and Banana

纵有疾风起

题目大意

一堆科学家研究猩猩的智商,给他M种长方体,每种N个。然后,将一个香蕉挂在屋顶,让猩猩通过 叠长方体来够到香蕉。

现在给你M种长方体,计算,最高能堆多高。要求位于上面的长方体的长要大于(注意不是大于等于)下面长方体的长,上面长方体的宽大于下面长方体的宽。

输入输出

开始一个数n,表示有多少种木块,木块的数量无限,然后接下来的n行,每行3个数,是木块的长宽高三个参量

输出使用这些在满足条件的情况下能够摆放的最大高度

解题思路

首先,我们严格令长>宽,可以想到一种木块有3种摆放方式,长、宽、高分别在下面。

对于摆放种类,我们可以使用dp动态规划来进行,看了其他博主写的博客,这个题和求最长递增子序列差不多(反过来想的,就是把塔给倒过来进行构造)。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=200;
struct node{
	int l, w, h;
	bool friend operator < (node a, node b)
	{
		if(a.h==b.h)
			return a.w > b.w;
		else 
			return a.l > b.l;
	}
}a[maxn];
int dp[maxn];
int main()
{
	int t=1, n;
	while(scanf("%d", &n) && n!=0)
	{
		int len = 0, x, y, z;
		for(int i=0; i<n; i++)
		{
			scanf("%d%d%d", &x, &y, &z);
			a[len].h=x; a[len].l= y>z? y:z; a[len++].w= y>z? z:y;
			a[len].h=y; a[len].l= x>z? x:z; a[len++].w= x>z? z:x;
			a[len].h=z; a[len].l= x>y? x:y; a[len++].w= x>y? y:x; 
		}
		sort(a, a+len);//排序是关键,最长递增子序列不用排序 
		for(int i=0; i<len; i++)
			dp[i]=a[i].h; //初始值是每一个长方体的高 
		int max_h, ans=0;
		for(int i=1; i<len; i++)
		{
			max_h=0;
			for(int j=0; j<i; j++)
			{
				if(a[j].l > a[i].l && a[j].w > a[i].w)
				{
					max_h = max_h > dp[j] ? max_h : dp[j];	
				}	
			} 
			dp[i]=a[i].h+max_h;
			ans=max(ans, dp[i]);
		}
		printf("Case %d: maximum height = %d
", t++, ans);
	}
	
	return 0;
 } 
欢迎评论交流!
原文地址:https://www.cnblogs.com/alking1001/p/11230571.html