HDOJ 1069 Monkey and Banana 解题报告
动态规划,最大上升子序列和。不同的是给的是长方体。
为了方便处理,笔者直接将每个长方体当做三个长方体处理,每个长方体的长大于等于宽。然后以长为主,宽为辅排序。
然后就和之前的那道FatMouse‘s speed一样了,当符合条件是,更新最大值。
下面是笔者第一次AC的代码:
#include <iostream> #include <algorithm> using namespace std; struct State { int length; int width; int height; int sum; } s[100]; int cmp(const State& a,const State& b) { if(a.length!=b.length) return (a.length<b.length); else return (a.width<b.width); } int main() { int i,j,n,max,cas=1,a,b,c; while(cin>>n && n) { for(i=0;i<n;i++) { cin>>a>>b>>c; if(a==b && b==c) s[i].height=s[i].length=s[i].width=s[i].sum=a; else { s[i+2].length=s[i+1].height=s[i].length=a>b?(a>c?a:c):(b>c?b:c); s[i+2].width=s[i+1].width=s[i].height=a<b?(a<c?a:c):(b<c?b:c); s[i+2].height=s[i+1].length=s[i].width=a+b+c-s[i].length-s[i].height; i+=2; n+=2; } } sort(s,s+n,cmp); max=s[0].sum=s[0].height; for(i=1;i<n;i++) { s[i].sum=s[i].height; for(j=0;j<i;j++) { if(s[i].length>s[j].length && s[i].width>s[j].width && s[i].sum<s[j].sum+s[i].height) { s[i].sum=s[j].sum+s[i].height; if(max<s[i].sum) max=s[i].sum; } } } cout<<"Case "<<cas++<<": maximum height = "<<max<<endl; } }
然后,笔者又把代码精简了一点点(笔者非常喜欢短一点。。。测试AC了):
#include <iostream> #include <algorithm> using namespace std; struct State { int length; int width; int height; int sum; } s[100]; int cmp(const State& a,const State& b) { if(a.length!=b.length) return (a.length<b.length); else return (a.width<b.width); } int main() { int i,j,n,max,cas=1,a,b,c; while(cin>>n && n) { for(i=0;i<n;i++) { cin>>a>>b>>c; if(a==b && b==c) s[i].height=s[i].length=s[i].width=s[i].sum=a; else { s[i+2].length=s[i+1].sum=s[i+1].height=s[i].length=a>b?(a>c?a:c):(b>c?b:c); s[i+2].width=s[i+1].width=s[i].sum=s[i].height=a<b?(a<c?a:c):(b<c?b:c); s[i+2].sum=s[i+2].height=s[i+1].length=s[i].width=a+b+c-s[i].length-s[i].height; i+=2; n+=2; } } sort(s,s+n,cmp); max=s[0].sum=s[0].height; for(i=1;i<n;i++) for(j=0;j<i;j++) if(s[i].sum<s[j].sum+s[i].height && s[i].length>s[j].length && s[i].width>s[j].width) if(max<(s[i].sum=s[j].sum+s[i].height)) max=s[i].sum; cout<<"Case "<<cas++<<": maximum height = "<<max<<endl; } }