使用单调栈在O(n)时间复杂度内计算直方图中的最大矩形面积
概述
使用单调栈在O(n)时间复杂度内计算直方图中的最大矩形面积。
清华大学邓俊辉老师数据结构课部分内容,本人课后的复述和理解。
代码
#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
struct point{//组合矩形
int h,//基础矩形条的高度
x,//本身位置
s,//起始矩形条位置
t,//末尾矩形条的下一位。4-2=2,其实是2和3两个点,3是末尾,4是下一位
area;//组合矩形的面积
void cal(){
area=h*(t-s);
}
}r[100],res;//每个矩形条都有扩展后的组合矩形,res是所求的最大面积矩形
int n=10,//矩形条数
ans=0;//最大组合矩形面积
void mk(){
for(int i=0;i<n;i++)r[i]=point{rand()%10,i,0,0};//随机设置每个矩形条的高度
}
void view(){
cout<<"显示\n";
cout<<"序号\t";for(int i=0;i<n;i++)cout<<setw(5)<<i<<"|\t";cout<<endl;
cout<<"高度\t";for(int i=0;i<n;i++)cout<<setw(5)<<r[i].h<<"|\t";cout<<endl;
for(int i=0;i<10;i++){
cout<<" \t";
for(int j=0;j<n;j++){
if(r[j].h>i)cout<<setw(5)<<"====="<<"|\t";
else cout<<setw(5)<<" "<<"|\t";
}
cout<<endl;
}
cout<<"左\t";for(int i=0;i<n;i++)cout<<setw(5)<<r[i].s<<"|\t";cout<<endl;
cout<<"右\t";for(int i=0;i<n;i++)cout<<setw(5)<<r[i].t<<"|\t";cout<<endl;
}
void find(){
stack<int> S;
/*
从该矩形条位置左右扩展,往左找到第一个不小于自己的矩形条,作为组合矩形的左。
同样,往右找到第一个不小于自己的矩形条,作为组合矩形的右。
(())()消一对()(),再消变成()
像消成对括号一样,用先进后出的堆
*/
for(int i=0;i<n;i++){//遍历所有矩形条
while(!S.empty()&&r[S.top()].h>=r[i].h)S.pop();//消除堆里左边不小于该矩形条的栈顶元素
r[i].s=S.empty()?0:S.top()+1;//栈空了就是第一个位置,否则就是栈顶元素的下一个位置。187593,3的左就是8
S.push(i);//非0矩形条放进堆
}
while(!S.empty())S.pop();
for(int i=n-1;i>=0;i--){
while(!S.empty()&&r[i].h<=r[S.top()].h)S.pop();//找组合矩形的右边界
r[i].t=S.empty()?n:S.top();
S.push(i);
}
for(int i=0;i<n;i++){
r[i].cal();
if(r[i].area>ans){
ans=r[i].area;res=r[i];
}
}
}
int main(){
srand(time(NULL));
mk();
//view();
find();
view();
cout<<ans<<endl;
cout<<"自身位置"<<res.x<<"\t高"<<res.h<<"\t起始位置:"<<res.s<<"\t结束位置:"<<res.t<<endl;
return 0;
}