一道非常简单的动态规划,做了很久。分析一下数据才知道排序写错了。
1.给出n种规格的箱子,每种有若干个
2.将箱子叠起来,求最高的高度,并符合一定要求
3.限制条件是叠起来的箱子每个在下面的箱子都比上面的箱子的长宽大。
理解题意很容易就可以入手了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> #include <algorithm> using namespace std; #define maxn 1000 int n; struct BLO { int x,y,z; bool operator < (const BLO& rhs) const{ return x < rhs.x || x==rhs.x && y < rhs.y; } }blo[maxn]; int d[maxn]; int dp() { for(int i=1;i<=n*3;i++) d[i] = blo[i].z; for(int j=1;j<=3*n;j++) { for(int i=1;i<j;i++) { if(blo[i].x<blo[j].x && blo[i].y<blo[j].y || blo[i].x<blo[j].y && blo[i].y<blo[j].x) { if(d[j] < d[i] + blo[j].z) { d[j] = d[i] + blo[j].z; } } } } int _max = -1; for(int i=1;i<=3*n;i++) { if(_max < d[i]) _max = d[i]; } return _max; } int main() { int tt=0; while(scanf("%d",&n) , n) { int cnt = 0; int a[4]; for(int i=1;i<=n;i++) { scanf("%d %d %d",&a[1],&a[2],&a[3]); sort(a+1,a+4); blo[++cnt].x=a[1],blo[cnt].y=a[2],blo[cnt].z=a[3]; blo[++cnt].x=a[2],blo[cnt].y=a[3],blo[cnt].z=a[1]; blo[++cnt].x=a[1],blo[cnt].y=a[3],blo[cnt].z=a[2]; } sort(blo+1,blo+1+n*3); printf("Case %d: maximum height = %d ", ++tt,dp()); } return 0; }
其实这道题做完做了很久,一个小时,因为排序错了,一直以为是动规写错了,分析数据就看到排序写错了。以后得注意啊。