algorithm-dev

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

View the Project on GitHub today2098/algorithm-dev

:heavy_check_mark: verify/aoj-DPL_3_C-largest_rectangle.test.cpp

Depends on

Code

#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/7/DPL/3/DPL_3_C"

#include <algorithm>
#include <iostream>
#include <vector>

#include "../algorithm/Others/largest_rectangle.hpp"

int main() {
    int n;
    std::cin >> n;

    std::vector<int> h(n);
    for(auto &in : h) std::cin >> in;

    auto &&ranges = algorithm::largest_rectangle(h);

    long long ans = 0;
    for(int i = 0; i < n; ++i) {
        const auto &[l, r] = ranges[i];
        long long tmp = (long long)h[i] * (r - l);
        ans = std::max(ans, tmp);
    }

    std::cout << ans << std::endl;
}
#line 1 "verify/aoj-DPL_3_C-largest_rectangle.test.cpp"
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/7/DPL/3/DPL_3_C"

#include <algorithm>
#include <iostream>
#include <vector>

#line 1 "algorithm/Others/largest_rectangle.hpp"



/**
 * @brief 最大長方形問題
 * @docs docs/Others/largest_rectangle.md
 */

#include <functional>
#include <stack>
#include <utility>
#line 13 "algorithm/Others/largest_rectangle.hpp"

namespace algorithm {

// 最大長方形問題.
// 各iにおいて,comp(H[i], H[] within [l,r))==true となるiを含む最大区間[l,r)を求める.O(N).
template <typename Type, class Compare = std::function<bool(const Type &, const Type &)> >
std::vector<std::pair<int, int> > largest_rectangle(
    const std::vector<Type> &h,
    const Compare &comp = [](const Type &a, const Type &b) -> bool { return a <= b; }) {
    const int n = h.size();
    std::vector<std::pair<int, int> > res(n, {0, n});  // res[i]:=(pair of [l,r)).
    std::stack<std::pair<Type, int> > st;
    // left side.
    for(int i = 0; i < n; ++i) {
        while(!st.empty() and comp(h[i], st.top().first)) st.pop();
        if(!st.empty()) res[i].first = st.top().second + 1;
        st.push({h[i], i});
    }
    // right side.
    st = std::stack<std::pair<Type, int> >();
    for(int i = n - 1; i >= 0; --i) {
        while(!st.empty() and comp(h[i], st.top().first)) st.pop();
        if(!st.empty()) res[i].second = st.top().second;
        st.push({h[i], i});
    }
    return res;
}

}  // namespace algorithm


#line 8 "verify/aoj-DPL_3_C-largest_rectangle.test.cpp"

int main() {
    int n;
    std::cin >> n;

    std::vector<int> h(n);
    for(auto &in : h) std::cin >> in;

    auto &&ranges = algorithm::largest_rectangle(h);

    long long ans = 0;
    for(int i = 0; i < n; ++i) {
        const auto &[l, r] = ranges[i];
        long long tmp = (long long)h[i] * (r - l);
        ans = std::max(ans, tmp);
    }

    std::cout << ans << std::endl;
}
Back to top page