201312-3 最大的矩形

201312-3 最大的矩形

问题描述

试题编号:201312-3
试题名称:最大的矩形
时间限制:1.0s
内存限制:256.0MB
问题描述:问题描述  在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n)个矩形的高度是hi。这n个矩形构成了一个直方图。例如,下图中六个矩形的高度就分别是3, 1, 6, 5, 2, 3。请添加图片描述
请找出能放在给定直方图里面积最大的矩形,它的边要与坐标轴平行。对于上面给出的例子,最大矩形如下图所示的阴影部分,面积是10。请添加图片描述
输入格式  第一行包含一个整数n,即矩形的数量(1 ≤ n ≤ 1000)。   第二行包含n 个整数h1, h2, … , hn,相邻的数之间由空格分隔。(1 ≤ hi ≤ 10000)。hi是第i个矩形的高度。输出格式  输出一行,包含一个整数,即给定直方图内的最大矩形的面积。样例输入6 3 1 6 5 2 3样例输出10
//单调栈
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while (cin >> n)
    {
        int height[1010], st[1010], weight[1010], pos = 0;
        long long sum = 0;
        memset(height, 0, sizeof(height));
        memset(st, 0, sizeof(st));
        memset(weight, 0, sizeof(weight));
        for (int i = 1; i <= n; i++)
            cin >> height[i];
        for (int i = 1; i <= n + 1; i++)
        {
            if (height[i] > st[pos])
                st[++pos] = height[i], weight[pos] = 1;
            else
            {
                int width = 0;
                while (st[pos] > height[i])
                {
                    width += weight[pos];
                    sum = max(sum, (long long)width * st[pos]);
                    pos--;
                }
                st[++pos] = height[i], weight[pos] = width + 1;
            }
        }
        cout << sum << endl;
    }
    return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while (cin >> n)
    {
        vector<int> height;
        stack<int> st;
        long long sum = 0, top;
        for (int i = 0; i < n; i++)
        {
            int temp;
            cin >> temp;
            height.push_back(temp);
        }
        height.push_back(-1);
        for (int i = 0; i < height.size(); i++)
        {
            if (st.empty() || height[st.top()] <= height[i])
                st.push(i);
            else
            {
                 while (!st.empty() && height[st.top()] > height[i])
                {
                    top = st.top();
                    st.pop();
                    //因为是下标运算
                    int temp = (i - top) * height[top];
                    if (temp > sum)
                        sum = temp;
                }
                st.push(top); //也就是说从之前的top到i都为i的值
                height[top] = height[i];
            }
        }
        cout << sum;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追寻远方的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值