poj 2559求柱形图中最大矩形
2014-05-08 00:16
267 查看
两种解法,其中一种是用单调栈。
我想到的是另外一种:最大的矩形,中间一定有个最矮的某个单位矩形,所以求出每个包含矩形histogram[i]的最大矩形的面积,输出这些面积中最大那个即可。
key:用两个数组记录histogram[i]左右两边第一个比它小的单位矩形的序号leftLowerId[i]和rightLowerId[i],那么对于histogram[i],它自己的最大矩形面积就是(rightLowerId[i] - leftLowerId[i] - 1) * histogram[i]。
这里找leftLowerId和rightLowerId的时候用DP加速。以rightLowerId为例,找到右边比histogram[i]矮的矩形,停止,遇到比histogram[i]高的矩形j,直接跳到比histogram[j]矮的矩形rightLowerId[j].
我想到的是另外一种:最大的矩形,中间一定有个最矮的某个单位矩形,所以求出每个包含矩形histogram[i]的最大矩形的面积,输出这些面积中最大那个即可。
key:用两个数组记录histogram[i]左右两边第一个比它小的单位矩形的序号leftLowerId[i]和rightLowerId[i],那么对于histogram[i],它自己的最大矩形面积就是(rightLowerId[i] - leftLowerId[i] - 1) * histogram[i]。
这里找leftLowerId和rightLowerId的时候用DP加速。以rightLowerId为例,找到右边比histogram[i]矮的矩形,停止,遇到比histogram[i]高的矩形j,直接跳到比histogram[j]矮的矩形rightLowerId[j].
#include<iostream> using namespace std; //the histogram stored from left to right long histogram[100001]; int rightLowerId[100001]; int leftLowerId[100001]; //from right to left void FindRightSideLowerRec(int n) { rightLowerId[n - 1] = n; // there is no rectangle on its right for (int i = n - 2; i >= 0; i--){ int cid = i + 1; while (histogram[cid] >= histogram[i] && cid < n){ cid = rightLowerId[cid]; // the key } rightLowerId[i] = cid; } } //from left to right void FindLeftSideLowerRec(int n) { leftLowerId[0] = -1; // there is no rectangle on its left for (int i = 1; i < n; i++){ int cid = i - 1; while (histogram[cid] >= histogram[i] && cid > -1){ cid = leftLowerId[cid]; // the key } leftLowerId[i] = cid; } } long long CalLargestRectangle(int n) { long long largestArea = 0; for (int i = 0; i < n; i++) { long long width = rightLowerId[i] - leftLowerId[i] - 1; long long height = histogram[i]; long long area = width * height; if (area > largestArea) largestArea = area; } return largestArea; } int main() { int n; while (scanf("%d", &n)){ if (n == 0) return 0; for (int i = 0; i < n; i++) { scanf("%d", &histogram[i]); } FindRightSideLowerRec(n); FindLeftSideLowerRec(n); long long larea = CalLargestRectangle(n); printf("%I64d\n", larea); } }
相关文章推荐
- Poj 2559 Largest Rectangle in a Histogram(柱形统计图中的最大矩形面积)
- poj 2559求柱形图中最大矩形
- POJ 2559 Largest Rectangle in a Histogram(单调栈维护最大矩形面积)
- POJ 2559 最大矩形。。
- poj2559(单调栈)最大矩形面积
- Poj 2559 最大矩形面积
- 连续区域最大矩形面积 POJ 1964 2082 2559 2796 3250 3494
- POJ 2559最大矩形面积
- POJ 2559 题解 最大矩形面积 单调栈
- Poj 2559 最大矩形面积
- POJ 2559 最大矩形面积 poj 3494
- 单调栈:柱形统计图中最大面积(POJ 2559)
- 单调栈:柱形统计图中最大面积(POJ 2559)
- Poj 2559 最大矩形面积 v单调栈 分类: Brush Mode 2014-11-13 20:48 81人阅读 评论(0) 收藏
- poj 2559 Largest Rectangle in a Histogram 求面积最大的矩形(单调栈)
- Poj 2559 最大矩形面积 v单调栈
- poj 2559 求连续的最大矩形面积(也可用于ccf最大连续矩形面积)
- Poj 2482 Stars in Your Window(用W*H的矩形去围住一个区域,使得这个区域内的星星的亮度最大)
- 计算最大矩形面积,POJ(2082)
- NYOJ-258/POJ-2559/HDU-1506 Largest Rectangle in a Histogram,最大长方形,dp或者单调队列!