题解 P6510 【奶牛排队】

· · 题解

解析

我自己做的时候把题意理解错了,交了很多遍,唉。

这道题其实也就是维护两个单调栈,s1 单调递减,s2 单调递增,注意栈里存储的是奶牛身高的下标,然后在 s1 里找出第一个小于等于 s2 栈顶的数,然后比较符合条件的数比较出最大值,就能找到答案了。

注意中间奶牛的身高是可以相等的。

写一个快读优化能节约很多时间。

AC代码

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
inline int read()
{
    int x=0,flag=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')flag=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch-'0');ch=getchar();}
    return x*flag;
}
int n,top1=0,top2=0,s1[N],s2[N],a[N];
unsigned long long ans=0; 
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
    {
        a[i]=read();
        while(top1!=0&&a[s1[top1]]>=a[i]) top1--;
        while(top2!=0&&a[s2[top2]]<a[i]) top2--;
        int k=upper_bound(s1+1,s1+1+top1,s2[top2])-s1;//STL
        if(k!=(top1+1)){if(ans<i-s1[k]+1) ans=i-s1[k]+1;}
        s1[++top1]=i;
        s2[++top2]=i;
    }
    printf("%lld",ans);
    return 0;
}