HDU:4252 A Famous City(单调栈)

来源:互联网 发布:小米nas网络私人云存储 编辑:程序博客网 时间:2024/06/08 23:50

题意:给一些从正面看得到的楼的高度,问最少可能有多少楼。

思路:单调栈。用一个栈维护一个单调递增序列。如果栈空或栈顶小于当前元素可将当前元素压栈,如果小于栈顶元素则将栈顶元素弹出并将答案加一,相同则无视。注意存在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;}


0 0
原创粉丝点击