NC50965 Largest Rectangle in a Histogram

NC50965 Largest Rectangle in a Histogram

題目

題目描述

A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:
img
Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

輸入描述

The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that \(1 \leq n \leq 100000\) . Then follow n integers \(h1\dots hn\), where \(0 \leq h_i \leq 1000000000\). These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

輸出描述

For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

示例1

輸入

7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0

輸出

8
4000

說明

Huge input, scanf is recommended.

題解

思路

知識點:單調棧。

如果枚舉區間,獲取區間最小直方,顯然是很複雜的。因為區間不同導致的最小值不同,雖然可以用單調隊列動態獲取某一區間的最小值,但問題在於端點的可能有 \(n^2\) 個,所以複雜度是 \(O(n^2)\) 是不可接受的。

但是換一種角度,我們枚舉直方,一共就 \(n\) 個,枚舉 \(n\) 次即可。那麼固定一個直方,最大的可伸展長度取決於左右第一個小於它的位置,找到長度乘以直方高度就是矩形面積了。

對於一個直方,左邊最鄰近小於用單調遞增棧從左到右維護,右邊同理從右到左維護,注意找到的位置是小於的那個直方的位置,而不是可伸展最大的位置,因此左邊的需要加一,右邊的需要減一。

時間複雜度 \(O(n)\)

空間複雜度 \(O(n)\)

程式碼

#include <bits/stdc++.h>

using namespace std;

int h[100007];
int l[100007], r[100007];
///最大矩形高度肯定是某個矩形高度
///對於一個矩形,水平擴展距離取決於第一個比他小的,兩邊都是
///於是對每個矩形,用單調遞增棧獲得他左側/右側第一個比它小的矩形位置,就能知道左側/右側擴展距離
int main() {
    std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int n;
    while (cin >> n, n) {
        for (int i = 0;i < n;i++) cin >> h[i];
        stack<int> s1;
        for (int i = 0;i < n;i++) {
            while (!s1.empty() && h[s1.top()] >= h[i]) s1.pop();
            l[i] = s1.empty() ? 0 : s1.top() + 1;///左側大於等於的第一個位置
            s1.push(i);
        }
        stack<int> s2;
        for (int i = n - 1;i >= 0;i--) {
            while (!s2.empty() && h[s2.top()] >= h[i]) s2.pop();///一定是大於等於,於是棧就是嚴格遞減棧,元素是最靠右的
            r[i] = s2.empty() ? n - 1 : s2.top() - 1;///右側大於等於的最後一個位置
            s2.push(i);
        }
        long long ans = 0;
        for (int i = 0;i < n;i++)
            ans = max(ans, (r[i] - l[i] + 1LL) * h[i]);
        cout << ans << '\n';
    }
    return 0;
}
Tags: