【题目链接】 http://poj.org/problem?id=3250
【题目大意】
有n头牛,每头牛都有一定的高度,他能看到在离他最近的比他高的牛前面的所有牛
现在每头牛往右看,问每头牛能看到的牛的数量的总和。
【题解】
单调栈维护每个数字右边第一个比其大的数字的位置,从后往前计算,
为保证最后一段计算的正确性,在最后一个位置后面加一个无限高的哨兵即可。
【代码】
#include <cstdio>
using namespace std;
const int N=80010;
typedef long long LL;
int st[N],top,n,a[N];
LL ans;
int main(){
while(~scanf("%d",&n)){
for(int i=0;i<n;i++)scanf("%d",&a[i]);
ans=top=0; a[st[top++]=n]=1000000000;
for(int i=n-1;i>=0;i--){
while(a[st[top-1]]<a[i])top--;
if(top)ans=ans+st[top-1]-i-1;
if(top&&a[st[top-1]]==a[i])st[top-1]=i;
else st[top++]=i;
}printf("%lld
",ans);
}return 0;
}