/* 求一个连续数组的最大矩形面积,可以用一个栈来做辅助,遍历整个数组a时将比当前值a[i]大的数组下标t压入栈,如果已保存下标t对应的a[t]比a[i]小,则将t抛出栈,计算此时的面积,因为存入栈中的都是说明比当前值大的数,而且里面的值也是按递减排列,所以高度就等于当前值 。而且要考虑栈内为空,所以要压入一个永远不被抛出栈的值,也就是最小值,所以i都是从1开始,然后因为每次计算面积时都是计算当前坐标的前一坐标对应的面积,所以最后n的个数要加1,然后最后一个赋值为0*/
#include <iostream>
#include<stack>
using namespace std;
const int N = 10;
void main() {
int n;
int a[N];
while (cin >> n&&n) {
for (int i = 1; i <= n; i++)
cin >> a[i];
}
stack<int> s;
s.push(0);
int sum = 0;
a[++n] = 0;
for (int i = 1; i <= n; i++) {
while (a[i] < a[s.top()]) {
int h = a[s.top()];
/*int w = i - s.top() ;
s.pop();*/ //此种写法是错误的 因为s.top()的值与i值相差不为1
s.pop();
int w = i - s.top()-1;
if (sum < w*h)
sum = w*h;
}
s.push(i);
}
cout << endl;
cout << sum;
}
如果变成二维的0,1数组,统计不为0的最大矩形元素个数,相同的解法,先把一维的连续的不为0的子数组求出,然后再按上面一维的方法向左右扩展的最大距离,求得最大矩阵矩阵。
<pre name="code" class="cpp">#include <iostream>
#include<stack>
using namespace std;
const int N = 10;
void main() {
int n,m;
int a[N];
int b[N][N];
while (cin >> n>>m) {
for (int i = 1; i <= n; i++)
for(int j = 1; j <= m;j++)
cin >> b[i][j];
}
memset(a, 0, sizeof(a));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
a[j] = b[i][j] == 0 ? 0:a[j]+1;
stack<int> s;
s.push(0);
int sum = 0;
a[++m] = 0;
for (int i = 1; i <= m; i++) {
while (a[i] < a[s.top()]) {
int h = a[s.top()];
/*int w = i - s.top() ;
s.pop();*/ //此种写法是错误的 因为i-s.top()的值与其高度不对应
s.pop();
int w = i - s.top()-1;
if (sum < w*h)
sum = w*h;
}
s.push(i);
}
cout << endl;
cout << sum;
}