您的位置:首页 > 其它

HDU:4252 A Famous City(单调栈)

2015-04-18 14:24 417 查看
题意:给一些从正面看得到的楼的高度,问最少可能有多少楼。

思路:单调栈。用一个栈维护一个单调递增序列。如果栈空或栈顶小于当前元素可将当前元素压栈,如果小于栈顶元素则将栈顶元素弹出并将答案加一,相同则无视。注意存在0的情况,即如果楼的高度是0不需要将该数字压栈。

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <map>
#include <stack>
#include <algorithm>
using namespace std;
int main()
{
    int n,kase=0;
    while(scanf("%d",&n)!=EOF)
    {
        int ans=0;
        stack<int> sk;
        for(int i=1; i<=n; ++i)
        {
            int x;
            scanf("%d",&x);
            while(!sk.empty()&&x<sk.top())
            {
                ans++;
                sk.pop();
            }
            if(sk.empty()||x>sk.top()) if(x!=0)sk.push(x);

        }
        while(!sk.empty())
        {
            ans++;
            sk.pop();
        }
        printf("Case %d: %d\n",++kase,ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: