BZOJ3956: Count
Description
Input
Output
Sample Input
3 2 0
2 1 2
1 1
1 3
2 1 2
1 1
1 3
Sample Output
0
3
3
HINT
M,N<=3*10^5,Ai<=10^9
考虑询问[l,r]区间中最大的元素A[i],则以[l,i)的元素作为左端点的好点对肯定不会穿过i,(i,r]的元素作为右端点的好点对肯定不会穿过i。
那么我们求出每个位置作为左右端点的答案,[l,r]的答案就是∑(ansl[j]|l<=j<i)+∑(ansr[j]|i<j<=r)
我们可以用单调栈来求,再前缀和起来累计答案。
维护一个严格递减的栈,胡乱搞搞就行了。
#include<cstdio> #include<cctype> #include<queue> #include<cmath> #include<cstring> #include<algorithm> #define rep(i,s,t) for(int i=s;i<=t;i++) #define dwn(i,s,t) for(int i=s;i>=t;i--) #define ren for(int i=first[x];i;i=next[i]) using namespace std; typedef long long ll; const int BufferSize=1<<16; char buffer[BufferSize],*head,*tail; inline char Getchar() { if(head==tail) { int l=fread(buffer,1,BufferSize,stdin); tail=(head=buffer)+l; } return *head++; } inline int read() { int x=0,f=1;char c=Getchar(); for(;!isdigit(c);c=Getchar()) if(c=='-') f=-1; for(;isdigit(c);c=Getchar()) x=x*10+c-'0'; return x*f; } const int maxn=300010; int n,m,type,A[maxn],maxv[20][maxn],Log[maxn]; int better(int a,int b) {return A[a]>A[b]?a:b;} int query(int l,int r) { int k=Log[r-l+1]; return better(maxv[k][l],maxv[k][r-(1<<k)+1]); } int S[maxn],top; ll suml[maxn],sumr[maxn],lastans; void init() { Log[0]=-1; rep(i,1,n) maxv[0][i]=i,Log[i]=Log[i>>1]+1; for(int j=1;(1<<j)<=n;j++) for(int i=1;i+(1<<j)-1<=n;i++) maxv[j][i]=better(maxv[j-1][i],maxv[j-1][i+(1<<j-1)]); S[top=1]=1; rep(i,2,n) { suml[i]=suml[i-1]; while(top&&A[i]>A[S[top]]) suml[i]++,top--; if(top) suml[i]++; while(top&&A[i]>=A[S[top]]) top--; S[++top]=i; } S[top=1]=n; dwn(i,n-1,1) { while(top&&A[i]>A[S[top]]) sumr[i]++,top--; if(top) sumr[i]++; while(top&&A[i]>=A[S[top]]) top--; S[++top]=i; } rep(i,2,n) sumr[i]+=sumr[i-1]; } ll solve(int l,int r) { int p=query(l,r); return sumr[p-1]-sumr[l-1]+suml[r]-suml[p]; } int main() { n=read();m=read();type=read(); rep(i,1,n) A[i]=read(); init(); while(m--) { int l=read(),r=read(); if(type) l=(l+lastans-1)%n+1,r=(r+lastans-1)%n+1; printf("%lld\n",lastans=solve(min(l,r),max(l,r))); } return 0; }