HDU 4252

单调栈: 基础知识 百度一哈

题目:http://acm.hdu.edu.cn/showproblem.php?pid=4252

单调栈 | 维护单调栈。每个矩形入栈时,判断它的高度是否大于等于栈顶矩形的高度,如果满足,则直接入栈。否则就向前找,一边出栈一边记录宽度,计算面积。知道找到第一个不满足条件的位置,然后将当前高度入栈。

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n, x, ans = 0, ca = 0;
    stack<int> s;
    while(cin >> n) {
        ans = 0;
        while(!s.empty()) s.pop();
        for(int i = 0; i < n; i++) {
            cin >> x;
            if(s.empty()) {
                if(x) s.push(x);
                continue;    
            }else {
                if(s.top() == x) {
                     continue;
                }else if(s.top() < x) {
                    s.push(x);
                }else { //
                    bool flag = true;
                    while(!s.empty()) {
                        if(s.top() > x) {
                            s.pop();
                            ans++;
                        }else if(s.top() == x) {
                            flag = false;
                            break;
                        }else {
                            if(x) s.push(x);
                            flag = false;
                            break;
                        }
                    }
                    if(flag && x != 0) {
                        s.push(x);
                    } 
                }
            }        
        }
        ans += s.size();
        ca++;
        printf("Case %d: %d
",ca,ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/JiaaaaKe/p/11255939.html