Largest Rectangle in a Histogram(矩阵的最大矩形面积)(动态规划)

Largest Rectangle in a Histogram

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23837 Accepted Submission(s): 7462

Problem Description

A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:

在这里插入图片描述

Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

Input

The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1 <= n <= 100000. Then follow n integers h1, …, hn, where 0 <= hi <= 1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

Output

For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

Sample Input
7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0

Sample Output
8
4000

解题分析:
题目要求的是,条形图里面积最大的矩形的面积,一开始思路是,可以先从左边第一个小矩形开始向右遍历,当作第一个小矩形是最矮的,看看接下来后面的矩形是否可以与它合并一个大矩形,先是第一个矩形开始,然后再从第二个矩形开始,…。依此类推,然后在从右边第一个开始遍历,如同左边一样。

注意的点:里面用long long 类型的符合似乎不能改,如果改为double或是int都会出现wrong answer(具体我也不知道怎么回事,小组限时训练wr了好多个,就错在这个int与long long,希望大家重视)

#include <iostream>
using namespace std;
const int maxn = 1e5 + 1000;
long long n, s = 0,max;
long long a[maxn], b[maxn], b2[maxn];
int main()
{
	while (scanf_s("%lld", &n) != EOF&&n)
	{
		
		
		for (int i=1;i <= n;i++)
		{
			cin >> a[i];
		}
		b[1] = 1;
		b2[n] = n;
		for (int i = 2;i <= n;i++)//遍历从左矩形到右,求出每个矩形左端非递减连续的下标
		{
			int temp = i;
			while (temp > 1 &&a[temp - 1]>=a[i])// a[i] <= 
			{
				temp = b[temp - 1];
			}
			b[i] = temp;
		}
		for (int i = n-1;i>0 ;i--)//遍历从右矩形到左,求出每个矩形右端非递减连续的下标
		{
			int temp = i;
			while (temp < n &&a[temp + 1]>= a[i])// <= 
			{
				temp = b2[temp + 1];
			}
			b2[i] = temp;
		}
		max = 0;
		for (int i = 1;i <= n;i++)
		{
			long long temp2 = (b2[i] - b[i] + 1)*a[i];
			if (temp2 > max) max = temp2;
		}
		cout << max << endl;
	}
}

大家加油丫丫丫丫

猜你喜欢

转载自blog.csdn.net/weixin_43697280/article/details/86619039
今日推荐