题目链接:https://www.luogu.com.cn/problem/P5906
思路:板子题
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <bitset>
#include <cmath>
#include <cctype>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll inff = 0x3f3f3f3f3f3f3f3f;
#define FOR(i,a,b) for(int i(a);i<=(b);++i)
#define FOL(i,a,b) for(int i(a);i>=(b);--i)
#define REW(a,b) memset(a,b,sizeof(a))
#define inf int(0x3f3f3f3f)
#define si(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define sd(a) scanf("%lf",&a)
#define ss(a) scanf("%s",a)
#define pb push_back
#define lc (d<<1)
#define Pll pair<ll,ll>
#define P pair<int,int>
#define pi acos(-1)
const int N=2e5+8;
int n,m,a[N],b[N],ds,ma[N],mi[N],c[N];
struct as{
int l,r,d,ss;}d[N];
bool cmp(as x,as y){return (b[x.l]!=b[y.l])?b[x.l]<b[y.l]:x.r<y.r;}
bool cmp1(as a,as b){return a.d<b.d;}
int cal(int l,int r)
{
int ans=0;
FOR(i,l,r) mi[a[i]]=mi[a[i]]?mi[a[i]]:i,ans=max(i-mi[a[i]],ans);
FOR(i,l,r) mi[a[i]]=0;
return ans;
}
unordered_map<int,int>mp;
int main()
{
cin.tie(0);
cout.tie(0);
cin>>n;
int zz=sqrt(n);
FOR(i,1,n)
{
si(a[i]),b[i]=i/zz+1;
if(!mp.count(a[i])) mp[a[i]]=++ds;
a[i]=mp[a[i]];
}
cin>>m;
FOR(i,1,m) si(d[i].l),si(d[i].r),d[i].d=i;
sort(d+1,d+m+1,cmp);
int l,r,qw=-1,ans;
ds=0;
FOR(i,1,m)
{
if(b[d[i].l]!=qw)
{
FOR(j,1,ds) mi[c[j]]=ma[c[j]]=0;
qw=b[d[i].l],l=min(qw*zz,n),r=l-1,ans=ds=0;
}
if(b[d[i].l]==b[d[i].r]) {d[i].ss=cal(d[i].l,d[i].r);continue;}
while(r<d[i].r)
{
r++,ma[a[r]]=r;
if(!mi[a[r]]) mi[a[r]]=r,c[++ds]=a[r];
ans=max(ans,r-mi[a[r]]);
}
int sd=ans,zz=l;
while(l>d[i].l)
{
l--;
if(ma[a[l]]) ans=max(ans,ma[a[l]]-l);
else ma[a[l]]=l;
}
while(l<zz)
{
if(ma[a[l]]==l) ma[a[l]]=0;
l++;
}
d[i].ss=ans;
ans=sd;
}
sort(d+1,d+m+1,cmp1);
FOR(i,1,m) printf("%d\n",d[i].ss);
return 0;
}