【题目描述】 李莳花要做一个架子,把她喜欢的摆件叠放起来,她的每个摆件的位置顺序是固 定的。这个架子的宽度是 W,每层排放的摆件不能超过这个宽度,每层架子的高度不 能低于最高的摆件的高度。假设,给出排列好的每个摆件的宽度 Wi,和高度 Hi,请 计算需要最少多高的架子。 【输入格式】 输入的第一行有 2 个数字,一个是摆件的个数 n,和架子的宽度 W。 以下摆件个数 n 行,每行的第一个数是摆件的宽度 Wi和高度 Hi。 【输出格式】 输出放置摆件架子的最低高度。 【样例输入】(测试数据不包含本样例) 5 5 2 1 1 2 1 3 2 3 2 2 【样例输出】 5 C++98代码
时间: 2024-04-08 08:34:23 浏览: 7
您好!根据您的描述,您需要计算放置摆件的架子的最低高度。根据题目要求,每层排放的摆件不能超过架子的宽度,并且每层架子的高度不能低于最高的摆件的高度。
为了解决这个问题,我将使用贪心算法来找到最低的架子高度。首先,按照摆件的高度进行排序,然后依次将摆件放置在架子上。
请看下面的解决方案:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
struct Decoration {
int width;
int height;
};
bool compareByHeight(const Decoration& deco1, const Decoration& deco2) {
return deco1.height > deco2.height;
}
int calculateMinHeight(int n, int W, const std::vector<Decoration>& decorations) {
std::sort(decorations.begin(), decorations.end(), compareByHeight);
int currentHeight = 0;
int currentWidth = 0;
int minHeight = 0;
for (int i = 0; i < n; i++) {
if (currentWidth + decorations[i].width <= W) {
currentWidth += decorations[i].width;
currentHeight = std::max(currentHeight, decorations[i].height);
} else {
minHeight += currentHeight;
currentHeight = decorations[i].height;
currentWidth = decorations[i].width;
}
}
minHeight += currentHeight;
return minHeight;
}
int main() {
int n, W;
std::cin >> n >> W;
std::vector<Decoration> decorations(n);
for (int i = 0; i < n; i++) {
std::cin >> decorations[i].width >> decorations[i].height;
}
int minHeight = calculateMinHeight(n, W, decorations);
std::cout << minHeight << std::endl;
return 0;
}
```
请输入摆件的个数n和架子的宽度W,然后按照每个摆件的宽度和高度输入。程序将输出放置摆件架子的最低高度。希望能帮到您!