TOP > 動的計画法
最大長方形(Largest-Rectangle)
説明
ヒストグラム中の最大長方形の面積を求める。
計算量
- $O(N)$
実装例
template< typename T >
int64_t largest_rectangle(vector< T > height)
{
stack< int > st;
height.push_back(0);
vector< int > left(height.size());
int64_t ret = 0;
for(int i = 0; i < height.size(); i++) {
while(!st.empty() && height[st.top()] >= height[i]) {
ret = max(ret, (int64_t) (i - left[st.top()] - 1) * height[st.top()]);
st.pop();
}
left[i] = st.empty() ? -1 : st.top();
st.emplace(i);
}
return (ret);
}
検証
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C"
#include "../../template/template.cpp"
#include "../largest-rectangle.cpp"
int main() {
int N;
cin >> N;
vector< int > h(N);
cin >> h;
cout << largest_rectangle(h) << endl;
}