Nyaan's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:heavy_check_mark: 最大長方形
(dp/maximal-rectangle.hpp)

最大長方形

概要

短く言うと、ヒストグラム中の長方形の最大面積を求める。

非負整数列$A$を入力とする。非負整数$l,r,h$ $(l \leq r \lt N)$が$h \leq A_i$ $(l \leq i \leq r)$ を満たすとき、$h(r-l+1)$の最大値を求める。

使い方

Verified with

Code

#pragma once

long long MaximalRectangle(vector<long long> buf) {
  int N = buf.size();
  buf.push_back(0);
  using P = pair<long long, long long>;
  stack<P> st;
  long long mx = 0;
  for (int i = 0; i <= N; i++) {
    P rect{buf[i], i};
    if (st.empty() or st.top().first < rect.first) {
      st.push(rect);
    } else {
      int j = i;
      while (!st.empty() and st.top().first >= rect.first) {
        P pre = st.top();
        st.pop();
        mx = max(mx, pre.first * (i - pre.second));
        j = pre.second;
      }
      rect.second = j;
      st.push(rect);
    }
  }
  return mx;
}

/**
 * @brief 最大長方形
 * @docs docs/dp/maximal-rectangle.md
 */
#line 2 "dp/maximal-rectangle.hpp"

long long MaximalRectangle(vector<long long> buf) {
  int N = buf.size();
  buf.push_back(0);
  using P = pair<long long, long long>;
  stack<P> st;
  long long mx = 0;
  for (int i = 0; i <= N; i++) {
    P rect{buf[i], i};
    if (st.empty() or st.top().first < rect.first) {
      st.push(rect);
    } else {
      int j = i;
      while (!st.empty() and st.top().first >= rect.first) {
        P pre = st.top();
        st.pop();
        mx = max(mx, pre.first * (i - pre.second));
        j = pre.second;
      }
      rect.second = j;
      st.push(rect);
    }
  }
  return mx;
}

/**
 * @brief 最大長方形
 * @docs docs/dp/maximal-rectangle.md
 */
Back to top page