题目详情
【解析】
【代码】
/********************************* * 日期: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 查看评论