【CCFCSP】201312-3 最大的矩形

試題編號: 201312-3
試題名稱: 最大的矩形
時間限制: 1.0s
內存限制: 256.0MB

本題的簡單做法很容易想到,可以直接遍歷矩形的起點,向後從這一矩形開始的所有矩形,找出最大面積,此時矩形的高度應該是所有矩形高度的最小值。
另一種做法是保持一個高度變高的棧,遇到比棧頂低的高度時出棧計算高度。

include

include

include

include

include

include

include

include

using namespace std;
int a[1010];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
int ans = 0;
for (int i = 1; i <= n; i++) {
int h = a[i];
for (int j = i; j <= n; j++) {
h = min(a[j], h);
ans = max(ans, h*(j - i + 1));
}
}
cout << ans << endl;
}
使用棧:
int main() {
int n
stacks;
cin >> n;
int ans = 0;
for (int i = 1; i <= n; i++) {
cin >> h[i];
if (s.empty()) {
s.push(i);
continue;
}
while (!s.empty() && h[i] < h[s.top()]) {
int t = s.top();
s.pop();
if (!s.empty()) {
ans = max(ans, h[t] * (i - s.top() - 1));
}

        else {
            ans = max(ans, h[t] * (i - 1));
        }
    }
    s.push(i);
}
while (!s.empty()) {
    int t = s.top();
    s.pop();
    if (!s.empty())
        ans = max(ans, h[t] * (t - s.top() + 1));
    else
        ans = max(ans, h[t] * n);
}
cout << ans << endl;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章