题目:
给定一个数组表示楼房高度,一个楼房高度一定是一样的,但长度可能很长,求最少的楼房数
说明:
第一个图中两个橙色的高度一样,如果按最少的算,它们可能是同一个建筑物,但红色和绿色比较高,所以最少为3栋楼,即橙色为一栋楼,红色和绿色分别为一栋楼
样本输入:
4
3 2 1 1
3
1 2 1
样本输出:
3
2
维护单调栈(注意相等时的情况)
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
typedef long long ll;
const int M=100005;
int a[M];
int main()
{
int n,cas=0;
while(cin>>n&&n)
{
stack<int>s;
int sum=0;
for(int i=1;i<=n;i++){
cin>>a[i];
if(s.empty()||a[i]>a[s.top()]){
s.push(i);
if(a[i]!=0)
sum++;
}
else
{
while(s.size()>1&&a[i]<a[s.top()])
s.pop();
if(a[i]<a[s.top()]){
s.pop();
s.push(i);
if(a[i]!=0)
sum++;
}
if(a[i]>a[s.top()])
{
s.push(i);
if(a[i]!=0)
sum++;
}
}
}
cout<<sum<<endl;
}
return 0;
}