Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

庞果网之寻找直方图中面积最大的矩形

$
0
0

题目详情

给定直方图,每一小块的height由N个非负整数所确定,每一小块的width都为1,请找出直方图中面积最大的矩形。


   如下图所示,直方图中每一块的宽度都是1,每一块给定的高度分别是[2,1,5,6,2,3]:



   那么上述直方图中,面积最大的矩形便是下图所示的阴影部分的面积,面积= 10单位。



   请完成函数largestRectangleArea,实现寻找直方图中面积最大的矩形的功能,如当给定直方图各小块的高度= [2,1,5,6,2,3] ,返回10。


【解析】

【代码】

/*********************************
*   日期:2013-11-24
*   作者:SJF0115
*   题号: 寻找直方图中面积最大的矩形
*   来源:http://hero.pongo.cn/Question/Details?ID=58&ExamID=56
*   结果:AC
*   来源:庞果网
*   总结:
**********************************/
#include<iostream>
#include<stack>
#include<vector>
#include<stdio.h>
#include<malloc.h>
using namespace std;

typedef struct Rec{
    int height;
    int width;
}Rec;

int LargestRectangleArea(vector<int> &height){
    int Max = 0,i;
    int n = height.size();
    //容错处理
    if(n <= 0){
        return 0;
    }
    Rec *rec = (Rec*)malloc(sizeof(Rec)*n);
    stack<Rec> stack;
    //初始化
    for(i = 0;i < n;i++){
        rec[i].height = height[i];
        rec[i].width = 1;
    }
    for(i = 0;i < n;i++){
        int h = rec[i].height;
        //如果栈空或者当前高度大于栈顶的矩形高度的时候就压入栈
        if(stack.empty() || h > stack.top().height){
            stack.push(rec[i]);
        }
        else{
            int preWidth = 0;
            //小于栈顶的矩形高度就弹出栈,更新最大的矩形面积
            while(!stack.empty() && h < stack.top().height){
                rec[i].width += stack.top().width;
                //当前面积
                int currentMax = stack.top().height * (stack.top().width + preWidth);
                //更新最大值
                if(Max < currentMax){
                    Max = currentMax;
                }
                preWidth += stack.top().width;
                //出栈
                stack.pop();
            }
            //等于栈顶的矩形高度
            while(!stack.empty() && h == stack.top().height){
                rec[i].width += stack.top().width;
                stack.pop();
            }
            //栈空
            if(stack.empty() || h > stack.top().height){
                stack.push(rec[i]);
            }
        }
    }
    //最后栈中只剩递增的序列
    int width = 0;
    while(!stack.empty()){
        int currentMax = stack.top().height * (stack.top().width + width);
        if(currentMax > Max){
            Max = currentMax;
        }
        width += stack.top().width;
        stack.pop();
    }
    return Max;
}

int main(){
    int i,n,Max,num;
    while(scanf("%d",&n) != EOF){
        vector<int> height;
        for(i = 0;i < n;i++){
            scanf("%d",&num);
            height.push_back(num);
        }
        Max = LargestRectangleArea(height);
        printf("%d\n",Max);
    }
    return 0;
}


作者:SunnyYoona 发表于2013-11-25 0:03:39 原文链接
阅读:98 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>