对栈有了一定得了解后,做了这道题:
在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n)个矩形的高度是hi。
这n个矩形构成了一个直方图。例如,下图中六个矩形的高度就分别是3, 1, 6, 5, 2, 3。
请找出能放在给定直方图里面积最大的矩形,它的边要与坐标轴平行。
对于上面给出的例子,最大矩形如下图所示的阴影部分,面积是10。
基本思路就是第一次输入矩形的高以后,并将其记录在一个结构体,同时在结构体记录矩形的宽,虽然是1,
但也需要记录,后面要用到,将此结构体变量入栈。然后每输入一个高并记录在结构体变量temp中,判断他
是否大于栈顶的高,若大于等于就入栈,否则,也就是小于栈顶的高,就计算栈顶的面积,并将栈顶的宽累
加到一个变量暂记为total_w,然后让其出栈,再次与栈顶比较,直到temp中的高大于等于栈顶元素的高后停
止,关键来了,将累加的total_w的值赋给temp的宽,目的可以在代码中体现出来。然后经过上面的重复输入,
判断,最后栈里剩下的肯定是递增排列的元素,挨个判断即可。通过代码,可能会理解的更深刻。。
- #include <iostream>
- #include <algorithm>
- #include <cstring>
- #include <cstdio>
- #include <cmath>
- #include <stack>
-
- using namespace std;
-
- struct node
- {
- int h;
- int w;
- };
- int main()
- {
- int n, totalw, maxn=0, cura;
- node temp;
- stack < node > s;
- cin >> n;
- for(int i=1; i<=n; ++i)
- {
- cin >> temp.h;
- temp.w=1;
- if(s.empty())
- s.push(temp);
- else
- {
- cura=totalw=0;
- if(temp.h>=s.top().h)
- s.push(temp);
- else
- {
- while(!s.empty())
- {
- if(temp.h<s.top().h)
- {
- totalw+=s.top().w;
- cura=totalw*s.top().h;
- if(cura>maxn)
- maxn=cura;
- s.pop();
- }
- else
- {
- break;
- }
- }
- temp.w+=totalw;
- s.push(temp);
- }
- }
- }
- totalw=cura=0;
- while(!s.empty())
- {
- totalw+=s.top().w;
- cura=s.top().h*totalw;
- if(cura>maxn)
- maxn=cura;
- s.pop();
- }
- cout << maxn << endl;
-
-
- return 0;
- }