10 3 7 4 12 2
逆向思维,求每头牛被其他牛看到的数量
cnt=0
i=0 10 cnt+=0
i=1 10 3 单增栈 cnt+=1 cnt=1
i=2 10 3 7->10 7 cnt+=1 cnt=2
i=3 10 7 4 cnt+=2 cnt=4
i=4 10 7 4 12->12 cnt=4
i=5 12 2 cnt=5
算法抽象:维护单增栈,cnt+=stack.size()-1陷阱 等高看不到
10 10
一个都看不到
10 5 10
答案应为1
所以这是一个严格单增栈,不能出现相等的元素!
坑:答案不能用int,要用long long
#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
//严格单增栈 ,严格!
void push(stack<int> &a,int b)
{
if(a.empty() || b<a.top())
{
a.push(b);
}
else
{
while(!a.empty() && b>=a.top())
{
a.pop();
}
a.push(b);//不要忘记让b入栈!!!
}
}
int main(){
int n;
long long ans=0;//易错:不要用int!!!
stack<int> a;
scanf("%d",&n);
while(n--)
{
int temp;
scanf("%d",&temp);
push(a,temp);
ans+=a.size()-1;
}
printf("%lld",ans);
return 0;
}