您的位置:首页 > 其它

给定整型数组,其中每个元素表示木板的高度,木板的宽度都相同,求这些木板拼出的最大矩形的面积。并分析时间复杂度。

2017-01-13 15:22 381 查看
给定整型数组,其中每个元素表示木板的高度,木板的宽度都相同,求这些木板拼出的最大矩形的面积。并分析时间复杂度。
#include <iostream>
#include <stack>
using namespace std;

typedef struct Node {
int w;
int h;
} Node; /* 矩形结构 */

stack<Node*> mystack;

Node** initNodeArr(int *arr, int len) {
Node** nodeArr = new Node*[len];
for (int i = 0; i < len; ++i) {
Node * node = new Node();
node->w = 1;
node->h = arr[i];
nodeArr[i] = node;
}
return nodeArr;
}

int findMaxRectangleArea(int *arr, int len) {
if (!arr) {
return 0;
}
Node** nodeArr = initNodeArr(arr, len);
int curArea = 0;
int maxArea = 0;
int totalWidth = 0;

for (int i = 0; i < len; ++i) {
if (mystack.empty()) {
mystack.push(nodeArr[i]);
} else {
//栈内元素高度非线性递增
if (mystack.top()->h <= nodeArr[i]->h) {
mystack.push(nodeArr[i]);
} else {
/*当插入元素小于栈顶, 需要整合,将大于插入元素高的元素出栈,
* 并以插入元素高度为准,宽度为出栈个数+插入元素宽度,
* 整合为新矩形*/
totalWidth = 0;
while (!mystack.empty()) {
if (mystack.top()->h > nodeArr[i]->h) {
totalWidth += mystack.top()->w;
mystack.pop();
} else {
break;
}
}
totalWidth += nodeArr[i]->w;
nodeArr[i]->w = totalWidth;
mystack.push(nodeArr[i]);
}
}
}

//计算最大面积
totalWidth = 0;
while (!mystack.empty()) {
totalWidth += mystack.top()->w;
if ((curArea = totalWidth * mystack.top()->h) > maxArea) {
maxArea = curArea;
}
mystack.pop();
}

return maxArea;
}

int main() {
int arr[] = { 5, 4, 3, 2, 4, 5, 0, 7, 8, 4, 6 };

cout << "maxArea: "
<< findMaxRectangleArea(arr, sizeof(arr) / sizeof(arr[0]));

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  木板最大面积
相关文章推荐