您的位置:首页 > 其它

直方图最大矩阵面积

2016-04-30 18:45 274 查看
直方图最大矩阵面积法:

给定n个非负整数,表示直方图的方柱的高度,同时,每个方柱的宽度假定都为1,找出直方图中最大的矩形面积。

如:给定高度为:2,1,5,6,2,3,最大面积为10.



程序实现:

#include <iostream>
#include <stack>
#include <algorithm>
#include <cstring>
using namespace std;

int LargestRectangleArea(vector<int>& height){
height.push_back(0);//为了统计,数组最后添加0,确保原数组的最后一位得到计算
stack<int> s;
int LargestArea = 0;
int temp,i=0;
while(i<(int)height.size()){
if(s.empty()||(height[i]>height[s.top()])){
s.push(i);
i++;
}
else{
temp = s.top();
s.pop();
LargestArea = max(LargestArea,height[temp]*(s.empty()?i:i-s.top()-1));
}
}
return LargestArea;
}
int main()
{
int a[] ={2,1,5,6,2,3};
vector<int> height(a,a+sizeof(a)/sizeof(int));
cout<<LargestRectangleArea(height)<<endl;
return 0;
}


运行结果:



转载请注明出处:

C++博客园:godfrey_88

http://www.cnblogs.com/gaobaoru-articles/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: