hdu-1506-Largest Rectangle in a Histogram(dp)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1506

题意:给出一个n个宽为1的长方形,之后给出第i个长方形的高a[i]。求出由n个长方形组成的图形所能构成的面积最大的长方形。

这道题曾经用单调栈做过,想了解的可以戳这里(py):https://blog.csdn.net/qq_41157137/article/details/84778190

基本思路:dp的核心就是用已知一个或多个条件推出未知,题目要求最大的面积,长方形的面积=底X高,由题中所给的要求可知,最大面积的长方形的高一定为所给的高中的一个,即给4个为高4 6 8 9的长方形,最大面积的长方形高一定为其中之一,不会出现1,3,5等等。确定了高后,再来想宽就会好想很多,对于长方形的每个高来说,对应的宽为向左右延伸到第一个小于高的位置。即给4个为高4 6 9 8的长方形,第一个高为4的长方形的宽为区间[1-4],第二个则为[2-4],第三个为[3-3],第四个为[3-4]。在用高乘宽得到面积。这时候看看复杂度O(n^2),暴力肯定凉了。

dp想法:从前往后推每个长方形宽的左边界,同时如果该长方形左边有比它高的,可以直接跳到该长方形的左边界(想清楚:)),同理从后往前推每个长方形宽的右边界。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <set>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
ll h[maxn];
ll r[maxn];
ll l[maxn];
int main(){
	ll n;
	while (scanf("%lld", &n) != EOF && n){
		for (int i = 1; i <= n; i++){
			scanf("%lld", &h[i]);
			r[i] = i;
			l[i] = i;
		}
		for (int i = 1; i <= n; i++){
			while (l[i] >= 2 && h[l[i] - 1] >= h[i])
				l[i] = l[l[i] - 1];
		}
		ll MAX = -1;
		for (int i = n; i >= 1; i--){
			while (r[i] < n&&h[r[i] + 1] >= h[i])
				r[i] = r[r[i] + 1];
			MAX = max(MAX, h[i] * (r[i] - l[i] + 1));
		}
		printf("%lld\n", MAX);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42792291/article/details/85301472