RT,代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=2e6+10;
int n,q;
int max_where[N],min_where[N],max_where2[N],min_where2[N];
int c[N],b[N],ANS[N];
int kk,now,len,where[N],l_where[N],r_where[N];
struct node{
int l,r,id;
}Q[N];
bool cmp(node a,node b){
if(where[a.l]!=where[b.l]) return where[a.l]<where[b.l];
return a.r<b.r;
}
void solve(){
cin>>n;
for(int i=1;i<=n;i++) cin>>c[i],b[i]=c[i];
int idx=n;
sort(b+1,b+n+1),idx=unique(b+1,b+idx+1)-(b+1);
for(int i=1;i<=n;i++) c[i]=lower_bound(b+1,b+idx+1,c[i])-b;
len=sqrt(n),kk=n/len,now=1;
for(;now<=kk;now++) l_where[now]=r_where[now-1]+1,r_where[now]=l_where[now]+len-1;
if(r_where[now]<n) now++,l_where[now]=r_where[now-1]+1,r_where[now]=n;
for(int i=1;i<=n;i++) where[i]=(i-1)/len+1;
cin>>q;
for(int i=1;i<=q;i++) cin>>Q[i].l>>Q[i].r,Q[i].id=i;
sort(Q+1,Q+q+1,cmp);
int l=1,r=0,last_where=0,last_l=0;
int maxx=0,now_max=0;
for(int i=1;i<=q;i++){
if(where[Q[i].l]==where[Q[i].r]){
now_max=0;
for(int j=Q[i].l;j<=Q[i].r;j++) min_where2[c[j]]=(!min_where2[c[j]]?j:min_where2[c[j]]),max_where2[c[j]]=j;
for(int j=Q[i].l;j<=Q[i].r;j++) now_max=max(now_max,(max_where2[c[j]]-min_where2[c[j]])),max_where2[c[j]]=min_where2[c[j]]=0;
ANS[Q[i].id]=now_max;
}
else{
if(where[Q[i].l]!=last_where){
while(r>r_where[Q[i].l]) min_where[c[r]]=min(min_where[c[r]],r),max_where[c[r]]=r,r--;
while(l<r_where[Q[i].l]+1) max_where[c[l]]=max(max_where[c[l]],l),min_where[c[l]]=l,l++;
last_where=where[Q[i].l];
maxx=0;
}
while(r<Q[i].r){
r++;
if(!min_where[c[r]]) min_where[c[r]]=max_where[c[r]]=r;
else max_where[c[r]]=r;
maxx=max(maxx,max_where[c[r]]-min_where[c[r]]);
}
now_max=maxx;
last_l=l;
while(last_l>Q[i].l){
last_l--;
if(!min_where[c[last_l]]) min_where2[c[last_l]]=max_where2[c[last_l]]=last_l;
else min_where2[c[last_l]]=last_l,max_where2[c[last_l]]=max_where[c[last_l]];
now_max=max(now_max,max_where2[c[last_l]]-min_where2[c[last_l]]);
}
while(last_l<l){
min_where2[c[last_l]]=max_where2[c[last_l]]=0,last_l++;
}
ANS[Q[i].id]=now_max;
}
}
for(int i=1;i<=q;i++){
cout<<ANS[i]<<"\n";
}
}
signed main(){
solve();
return 0;
}