【C++】单调栈求最大矩形面积

选做题(单调栈的应用):

给定n个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为1。求在该柱状图中,能够勾勒出来的矩形的最大面积。

    图 1 柱状图示例

图1是柱状图的示例,给定的高度为,所能勾勒出来的矩形如图2所示,这些矩形最大面积为10(对应从左数第3个矩形)。

 

                                                                  图 2 所能勾勒出来的矩形

样例输入:

2 1 5 6 2 3

样例输出:

扫描二维码关注公众号,回复: 13146007 查看本文章

10

 

//单调栈的应用
//author:Mitchell_Donovan
//date:3.23
#include<iostream>
using namespace std;

class arrayStack {
private:
	int size;
	int top;
	int** stack;
public:
	arrayStack(int sizeValue) {
		size = sizeValue;
		stack = new int* [size];
		for (int i = 0; i < size; i++) {
			stack[i] = new int[2];
			stack[i][0] = stack[i][1] = -1;
		}
		top = 0;
	}
	~arrayStack() {
		for (int i = 0; i < size; i++) {
			delete[]stack[i];
		}
		delete[]stack;
	}
	bool push(int rank, int number) {
		if (top == size - 1) {
			cout << "The stack has been full!" << endl;
			return false;
		}
		top += 1;
		stack[top][0] = rank;
		stack[top][1] = number;
		return true;
	}
	bool pop() {
		if (top == 0) {
			cout << "The stack is empty!" << endl;
			return false;
		}
		stack[top][0] = stack[top][1] = -1;
		top -= 1;
		return true;
	}
	void getmax(int*array,int arraySize) {//2 1 4 4 5 1 3
		int area = 0;
		for (int i = 0; i < arraySize; i++) {
			if (array[i] > stack[top][1]) {
				push(i, array[i]);
			}
			else if (array[i] < stack[top][1]) {
				while (array[i] < stack[top][1]) {
					int height = stack[top][1];
					int width = i - stack[top - 1][0] - 1;
					area = max(height * width, area);
					pop();
				}
				push(i, array[i]);
			}
		}
		cout <<"The largest area is "<< area << endl;
	}
};
int main() {
	int arraySize;
	cout << "Please input the number of rectangles:";
	cin >> arraySize;
	int* array = new int[arraySize + 2];
	array[0] = 0;
	cout << "Please input the value of each rectangle:";
	for (int i = 1; i < arraySize + 1; i++) {
		cin >> array[i];
	}
	array[arraySize + 1] = 0;
	arrayStack test(arraySize + 2);
	test.getmax(array, arraySize + 2);
}

 

猜你喜欢

转载自blog.csdn.net/Mitchell_Donovan/article/details/115117785