week5作业A

题意:
给一个直方图,求直方图中的最大矩形的面积。例如,下面这个图片中直方图的高度从左到右分别是2, 1, 4, 5, 1, 3, 3, 他们的宽都是1,其中最大的矩形是阴影部分。
在这里插入图片描述
input:
输入包含多组数据。每组数据用一个整数n来表示直方图中小矩形的个数,你可以假定1 <= n <= 100000. 然后接下来n个整数h1, …, hn, 满足 0 <= hi <= 1000000000. 这些数字表示直方图中从左到右每个小矩形的高度,每个小矩形的宽度为1。 测试数据以0结尾。
output:
对于每组测试数据输出一行一个整数表示答案。
sample input:
7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0
sample output:
8
4000
思路:
输入数据,当输入n为0时程序结束。定义两个数组进行存储数据。将输入当数据存储在一个数组中。如果此时输入当数据大于stack数组中的第一个数据,就将数据存入stack中,存储宽度当数组也加一。如果数据小于等于比stack中的数据,就对两个形成当矩阵面积进行比对,最终输出矩阵面积较大的面积的值。
代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stack>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
 	if(n==0)
 	    break;
    int a[100050],w[100050];
    int stack[100050];
    int top=0;
    long long ans=0;
    memset(a,0,sizeof(a));
    for(int i=0;i<n;i++)
    {   	
 	    cin>>a[i];
    } 
    for(int i=0;i<=n;i++)
    {
        if(a[i]>stack[top])
        {
            stack[++top]=a[i];
            w[top]=1; 
        }
        else
        {
            int width=0;
            while(stack[top]>a[i])
            {
                width+=w[top];
                if(ans<(long long)width*stack[top])                    ans=(long long)width*stack[top];
                top--;
            }
            top++;
            stack[top]=a[i];
            w[top]=width+1;
        }
    }    cout<<ans<<endl;
    } 
    return 0;
 } 
发布了19 篇原创文章 · 获赞 0 · 访问量 208

猜你喜欢

转载自blog.csdn.net/weixin_45117273/article/details/105328578