faebdc的烦恼[st表]

传送门

题目说a[i]递增 , 极大降低了难度

我们将一样的几个点缩成一个点 , 记录l , r , num 表示缩的这个点对应的原区间以及长度

记录pos 表示这个点对应缩的哪个点

然后直接对num 用st表

查询即为max(rmq(pos[x]+1,pos[y]-1),r[pos[x]]-x+1,y-l[pos[y]]+1)


#include<bits/stdc++.h>
#define N 100050
using namespace std;
int n,q,a[N],l[N],r[N],pos[N]; 
int tot,st[N][20],Log[N];
int rmq(int l,int r){
	if(l>r) return 0;
	int b = Log[r-l+1];
	return max(st[l][b],st[r-(1<<b)+1][b]);
}
int main(){
	scanf("%d%d",&n,&q);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	int last=1,now=1;
	while(now<=n){
		tot++;
		while(a[now] == a[last]) pos[now]=tot , now++;
		l[tot]=last , r[tot]=now-1 , st[tot][0]=now-last , last=now;
	}
	for(int i=2;i<=tot;i++) Log[i]=Log[i/2]+1;
	for(int i=1;i<=17;i++)	
		for(int j=1;j<=tot;j++)
			st[j][i] = max(st[j][i-1] , st[j + (1<<(i-1))][i-1]);
	while(q--){
		int x,y,ans=0; scanf("%d%d",&x,&y);
		int p1 = pos[x] , p2 = pos[y];
		if(p1==p2){printf("%d\n",y-x+1); continue;}
		ans = max(ans , r[p1]-x+1);
		ans = max(ans , y-l[p2]+1);
		ans = max(ans , rmq(p1+1,p2-1));
		printf("%d\n",ans);
	}
}

猜你喜欢

转载自blog.csdn.net/sslz_fsy/article/details/84405005