Link
http://acm.hdu.edu.cn/showproblem.php?pid=1069
Description
Intention
给定 n n n个长方体的长、宽、高,各个长方体的长宽高输入顺序不一定相同,问你 n n n个长方体叠起来的最大高度是多少,两个长方体可以堆一起需要上面的立方体的长和宽小于下面的。对于一个长方体,你可以以不同的方式放置它,从而它的长宽高的组合也就有了很多种。每个长方体有无数个。
Input
1
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
0
Output
Case 1: maximum height = 40
Case 2: maximum height = 21
Case 3: maximum height = 28
Case 4: maximum height = 342
Solution
对于每个长方体,考虑三种放置方式,让输入的三个边,每个都成为高,另外的两个边成为长和宽,让较长的边成为长,较短的成为宽。这样所有的正方体的放置情况,我们都可以得到。然后把他们按照底部的大小排序,优先按长排序,其次按宽排序,最后按高排序,那么按照顺序来,有取与不取的情况,目标是为了获得高的最大值,就可以dp了。
Code
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
using namespace std;
#define inf 0x7f7f7f7f
#define maxn 500006
#define N 1
#define P 2
typedef long long ll;
typedef struct {
int u, v, next, w;
} Edge;
Edge e[20006];
int cnt, head[10006];
inline void add(int u, int v,int w) {
e[cnt].u = u;
e[cnt].v = v;
e[cnt].w = w;
// e[cnt].f=f;
e[cnt].next = head[u];
head[u] = cnt++;
e[cnt].u = v;
e[cnt].v = u;
e[cnt].w = w;
// e[cnt].f=-f;
e[cnt].next = head[v];
head[v] = cnt++;
}
inline void write(int x) {
if (x < 0)
putchar('-'), x = -x;
if (x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x * f;
}
struct rectangle{
int l,w,h,area;
}r[40];
int n,dp[100],t;
bool compare(rectangle a,rectangle b){
if(a.l!=b.l)return a.l>b.l;
if(a.w!=b.w)return a.w>b.w;
return a.h>b.h;
}
int main(){
while(scanf("%d",&n)&&n) {
t++;
int x, y, z,cot=0;
memset(dp,0,sizeof(dp));
for (int i = 0; i < n ; i++) {
x=read(),y=read(),z=read();
r[cot].h=x,r[cot].l=max(y,z),r[cot++].w=min(y,z);
r[cot].h=y,r[cot].l=max(x,z),r[cot++].w=min(z,x);
r[cot].h=z,r[cot].l=max(x,y),r[cot++].w=min(x,y);
}
sort(r,r+cot,compare);
int res=-1;
for(int i=0;i<cot;i++) {
dp[i]=r[i].h;
for (int j = 0; j < i; j++) {
if (r[j].l > r[i].l && r[j].w > r[i].w)
dp[i] = max(dp[i], dp[j] + r[i].h);
res = max(dp[i], res);
}
}
printf("Case %d: maximum height = %d\n",t,res);
}
}
我们坚持一件事情,并不是因为这样做了会有效果,而是坚信,这样做是对的。
——哈维尔