天天看点

CCF CSP 201312 3.最大的矩形

直方图dp。

上篇说过了,一模一样。但是这个题的结果不会溢出。

  • 一种是我上一篇的方法,从中间开始往两头找,同时利用了历史信息。
  • 另一种是我两年前写的方法,比较直观地枚举两端点,构成一个区间,一共枚举

    n(n+1)/2

    对首尾端点(一定要包括首尾端点重合的

    n

    种情况! 例子:

    151

    )。每次找出这个区间内的最小高度(这个最小高度就是以这个区间首尾作为底边的最大矩形的高,木板效应)。区间最小高度在左端点不变、右端点往右移动的过程中可以传递下去,因为它只会变得越来越小。

第一个:

#include <iostream>
#include <algorithm>
using namespace std;

int N;
int h[1001];
int l[1001], r[1001];
int ans = -1;

int main()
{
	scanf("%d", &N);
	for (int i = 1; i <= N; i++)
		scanf("%d", &h[i]);

	int t;
	l[1] = 1;
	for (int i = 2; i <= N; i++)
	{
		for (t = i; t - 1 >= 1 && h[t - 1] >= h[i]; t = l[t - 1]);
		l[i] = t;
	}

	r[N] = N;
	for (int i = N - 1; i >= 1; i--)
	{
		for (t = i; t + 1 <= N && h[t + 1] >= h[i]; t = r[t + 1]);
		r[i] = t;
	}

	for (int i = 1; i <= N; i++)
		ans = max(ans, h[i] * (r[i] - l[i] + 1));

	printf("%d\n", ans);

	return 0;
}
           

第二个:

#include <iostream>
#include <algorithm>
using namespace std;                     // 固定左端点,枚举右端点,区间最小高度在路径上传递,O(N^2)复杂度,N大于10000就不行了

int N;
int h[1001];
int ans = -1;

int main()
{
	scanf("%d", &N);
	for (int i = 1; i <= N; i++)
		scanf("%d", &h[i]);

	for (int i = 1; i <= N; i++)
	{
		int t = h[i];
		for (int j = i; j <= N; j++)              // 这里一定要从i开始枚举
		{
			if (h[j] < t) t = h[j];
			ans = max(ans, t*(j - i + 1));
		}
	}
	printf("%d\n", ans);

	return 0;
}