http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=93
题目:有若干种方块,每个方块的各个面都可以当作底面,请问方块能叠加的最大高度(相邻方块接触面边长必须不等)?
解法:题目的意思让人自然想到一种方案:对于最小的方块,能叠加的高度即为自身高度;对于第二小的方块,能叠加的高度为自身高度+最小方块能叠加的高度;……
这里存在两个问题:1. 如何衡量方块的“大小”;2. 对于某一方块,其上可能叠加若干种方块。
对于第1个问题,题目已经说明,相邻接触面的边长必须严格不等,因此方块a大于方块b的前提是a的两条边长严格大于b的。但是我们还漏了一点,即a的一条边大于b,另一条边小于b,此时a和b不能比较。不过这显然不碍事,因为排序的时候小于a的必定在a之前,大于a的必定在a之后,无法比较的在a前或a后都无所谓。
对于第2个问题,只需要遍历一边比当前方块小的即可。
#include <iostream>
#include <string.h>
#include <vector>
#include <math.h>
#include <stdio.h>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
class Block
{
public:
int x, y, z;
public:
Block(int x, int y, int z) : x(x), y(y), z(z){}
bool operator < (const Block& other) const
{
return x * y < other.x * other.y;
}
};
int n;
int caseId = 1;
vector<Block> v;
int maxHeight[180];
int main()
{
while (cin >> n && n > 0)
{
int x, y, z;
v.clear();
for (int i = 0; i < n; i++)
{
cin >> x >> y >> z;
v.push_back(Block(x, y, z));
v.push_back(Block(x, z, y));
v.push_back(Block(y, x, z));
v.push_back(Block(y, z, x));
v.push_back(Block(z, x, y));
v.push_back(Block(z, y, x));
}
sort(v.begin(), v.end());
int max = 0;
for (int i = 0; i < v.size(); i++)
{
if (i == 0)
maxHeight[i] = v[i].z;
else
{
for (int j = 0; j < i; j++)
if (v[j].x < v[i].x && v[j].y < v[i].y && max < maxHeight[j])
max = maxHeight[j];
maxHeight[i] = max + v[i].z;
}
}
for (int i = 0; i < v.size(); i++)
if (max < maxHeight[i])
max = maxHeight[i];
printf("Case %d: maximum height = %d\n", caseId++, max);
}
}