HDU 1506(Largest Rectangle in a Histogram)

本题与 HDU 1505 类似,将二维转换为一维即可。

#include 
#include 
const int MAXN = 100005;

__int64 h[MAXN]; //矩形的高
int l[MAXN], r[MAXN]; //以每个小矩形的高作为大矩形的高,大矩形的左边缘和右边缘

int main()
{
	int n;
	while (scanf("%d", &n))
	{
		if (n == 0)
			break;
		memset(h, 0, sizeof(h));
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &h[i]);
		}

		h[0] = h[n + 1] = -1;
		for (int i = 1; i <= n; i++) //查找每个左边缘
		{
			l[i] = i;
			int j = i - 1;
			while (h[j] >= h[i])
			{
				l[i] = l[l[j]];
				j = l[j] - 1;
			}
		}
		for (int i = n; i >= 1; i--) //查找每个右边缘
		{
			r[i] = i;
			int j = i + 1;
			while (h[j] >= h[i])
			{
				r[i] = r[r[j]];
				j = r[j] + 1;
			}
		}
		__int64 maxArea = -0x3f3f3f3f; //大矩形最大面积
		for (int i = 1; i <= n; i++)
		{
			if (h[i] * (r[i] - l[i] + 1) > maxArea)
				maxArea = h[i] * (r[i] - l[i] + 1);
		}
		printf("%I64d\n", maxArea);
	}
	return 0;
}

继续加油。

你可能感兴趣的:(HDU)