枚举,二分,$RMQ$。
对于一个序列来说,如果固定区间左端点,随着右端点的增大,最大值肯定是非递减的,最小值肯定是非递增的。
因此,根据这种单调性,我们可以枚举区间左端点$L$,二分找到第一个位置${{p_1}}$,使得$\mathop {\max }\limits_{i = L}^{{p_1}} {a_i} = \mathop {\min }\limits_{i = L}^{{p_1}} {b_i}$;再次二分找到最后一个位置${{p_2}}$,使得$\mathop {\max }\limits_{i = L}^{{p_2}} {a_i} = \mathop {\min }\limits_{i = L}^{{p_2}} {b_i}$。那么以$L$为左端点的区间,有${{p_2}}-{{p_1}}+1$个。查询区间最值的话可以倍增预处理一下。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-6; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } template <class T> inline void read(T &x) { char c = getchar(); x = 0; while(!isdigit(c)) c = getchar(); while(isdigit(c)) { x = x * 10 + c - ‘0‘; c = getchar(); } } const int maxn=200010; int a[maxn],b[maxn],n; int MAX[maxn][30],MIN[maxn][30]; void RMQ_init() { for(int i=0;i<n;i++) MAX[i][0]=a[i],MIN[i][0]=b[i]; for(int j=1;(1<<j)<=n;j++) for(int i=0;i+(1<<j)-1<n;i++) MAX[i][j]=max(MAX[i][j-1],MAX[i+(1<<(j-1))][j-1]), MIN[i][j]=min(MIN[i][j-1],MIN[i+(1<<(j-1))][j-1]); } int RMQ_MAX(int L,int R) { int k=0; while((1<<(k+1))<=R-L+1) k++; return max(MAX[L][k],MAX[R-(1<<k)+1][k]); } int RMQ_MIN(int L,int R) { int k=0; while((1<<(k+1))<=R-L+1) k++; return min(MIN[L][k],MIN[R-(1<<k)+1][k]); } int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); for(int i=0;i<n;i++) scanf("%d",&b[i]); RMQ_init(); LL ans=0; for(int i=0;i<n;i++) { if(b[i]<a[i]) continue; int p1=-1,p2=-1; int L=i,R=n-1; while(L<=R) { int mid=(L+R)/2; int mx=RMQ_MAX(i,mid),mn=RMQ_MIN(i,mid); if(mx>mn) R=mid-1; else if(mx==mn) R=mid-1,p1=mid; else L=mid+1; } L=i,R=n-1; while(L<=R) { int mid=(L+R)/2; int mx=RMQ_MAX(i,mid),mn=RMQ_MIN(i,mid); if(mx>mn) R=mid-1; else if(mx==mn) L=mid+1,p2=mid; else L=mid+1; } if(p1==-1) continue; ans=ans+(LL)(p2-p1+1); } printf("%lld\n",ans); return 0; }
时间: 2024-12-12 01:08:27