先写了一个好大量内存的O(n^3)的代码,TLE~ 贴下,看看能不能再优化。
#include <iostream>
#include <stdio.h>
using namespace std;
struct block
{
int het;
int len;
int wid;
};
block dp[100],dp1[2][2000000];
int main()
{
int x,y,z,n,i,j,k,in,ans,e,cas;
//block dp[100],dp1[2][10000];
cas = 1;
while(scanf("%d",&n)!=EOF&&n)
{
i = 0;
ans = 0;
while(n --)
{
scanf("%d%d%d",&x,&y,&z);
if(x == y&&y == z) {dp[i].het = x;dp[i].len = y;dp[i++].wid = z;}
else {
dp[i].het = x;dp[i].len = y;dp[i++].wid = z;
dp[i].het = y;dp[i].len = x;dp[i++].wid = z;
dp[i].het = z;dp[i].len = x;dp[i++].wid = y;
}
}
n = i;
for(i = 0;i < n;i ++)
dp1[0][i] = dp[i];
e = 1;
while(i != 0)
{
in = i;
i = 0;
e = 1 - e;
for(j = 0;j < in;j ++)
{
for(k = 0;k < n;k ++)
{
if((dp[k].len < dp1[e][j].len&&dp[k].wid < dp1[e][j].wid)||(dp[k].wid < dp1[e][j].len&&dp[k].len < dp1[e][j].wid))
{
dp1[1-e][i].het = dp1[e][j].het + dp[k].het;
dp1[1-e][i].len = dp[k].len;
dp1[1-e][i].wid = dp[k].wid;
i ++;
}
}
}
}
//cout<<in<<endl;
for(i = 0;i < in;i ++)
{
if(dp1[e][i].het > ans) ans = dp1[e][i].het;
}
printf("Case %d: maximum height = %d\n",cas ++,ans);
}
return 0;
}
后来没思路了,上网看了一个很好的算法,类似求最长子序列。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
struct block
{
int het;
int len;
int wid;
};
block dp[100];
int cmp(const void *a,const void *b)
{
if((*(block* )a).len != (*(block* )b).len)
return (*(block* )b).len - (*(block* )a).len;
else
return (*(block* )b).wid - (*(block* )a).wid;
}
int main()
{
int a[3],n,i,j,k,in,ans,e,cas,maxi;
cas = 1;
while(scanf("%d",&n)!=EOF&&n)
{
i = 0;
ans = 0;
while(n --)
{
scanf("%d%d%d",&a[0],&a[1],&a[2]);
sort(a,a+3); //这里要排序,在其后的比较中简化
dp[i].het = a[2];dp[i].len = a[1];dp[i++].wid = a[0];
dp[i].het = a[1];dp[i].len = a[2];dp[i++].wid = a[0];
dp[i].het = a[0];dp[i].len = a[2];dp[i++].wid = a[1];
}
qsort(dp,i,sizeof(dp[0]),cmp);
n = i;
for(i = 1;i < n;i ++)
{
maxi = 0;
for(j = 0;j < i;j ++)
{
if(dp[j].len > dp[i].len&&dp[j].wid > dp[i].wid)
{
if(dp[j].het > maxi) maxi = dp[j].het;
}
}
dp[i].het += maxi;
}
//for(i = 0;i < n;i ++)
//cout<<dp[i].len<<" "<<dp[i].wid<<" "<<dp[i].het<<endl;
for(i = 0;i < n;i ++)
if(dp[i].het > ans ) ans = dp[i].het;
printf("Case %d: maximum height = %d\n",cas ++,ans);
}
return 0;
}