题意:一排数字代表一排牛的高度,每头牛只能向右看到比自己矮的牛的头,也看不到比自己高或相等的牛右边的牛头。问一共有多少牛可以被看到。
思路;从右边牛开始,构建一个单调递增栈,遇到比栈顶高的牛,不断出栈,找到它能向右边看到的位置,计数中间能看到牛的个数,再进栈,作为栈顶。
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
long long h[80010];
stack<int>s;
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++) scanf("%lld",&h[i]);
h[n+1]=1<<30;
while(!s.empty()) s.pop();
s.push(n+1);
long long sum=0;
for(int i=n;i>0;i--)
{
int x=s.top();
while(h[x]<h[i])
{
s.pop();
x=s.top();
}
sum+=x-i-1;
s.push(i);
}
printf("%lld\n",sum);
}
return 0;
}