crz_qwq @ 2024-11-16 16:59:59
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
vector<int>mp[N];
int cnt[N];
int a[N],rk[N],id[N];
int L[N],R[N],pos[N],val[N];
int count(int l,int r,int k){return upper_bound(mp[k].begin(),mp[k].end(),r)-lower_bound(mp[k].begin(),mp[k].end(),l);}
int getMax(int x,int y,int l,int r)
{
if(x*y==0)
return x+y;
int t1=count(l,r,x),t2=count(l,r,y);
if(t1<t2)
return y;
if(t1==t2&&x>y)
return y;
return x;
}
int query(int l,int r)
{
int x=pos[l],y=pos[r];
if(x==y)
{
int ans=0;
for(int i=l;i<=r;++i)
ans=getMax(ans,a[i],l,r);
return ans;
}
int ans=0;
for(int i=x+1;i<y;++i)
ans=getMax(ans,val[i],l,r);
for(int i=l;i<=R[x];++i)
ans=getMax(ans,a[i],l,r);
for(int i=L[y];i<=r;++i)
ans=getMax(ans,a[i],l,r);
return ans;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;++i)
{
cin>>a[i];
rk[i]=a[i];
}
sort(rk+1,rk+n+1);
int t=sqrt(n),tot=unique(rk+1,rk+n+1)-rk-1;
for(int i=1;i<=n;++i)
{
int tmp=a[i];
a[i]=lower_bound(rk+1,rk+tot+1,a[i])-rk;
id[a[i]]=tmp;
mp[a[i]].emplace_back(i);
}
for(int i=1;i<=t;++i)
{
L[i]=(i-1)*t+1;
R[i]=i*t;
}
if(R[t]<n)
{
++t;
L[t]=R[t-1]+1;
R[t]=n;
}
for(int i=1;i<=t;++i)
{
for(int j=L[i];j<=R[i];++j)
{
pos[j]=i;
val[i]=getMax(val[i],a[j],L[i],R[i]);
}
}
int lst=0;
while(m--)
{
int l,r;
cin>>l>>r;
l=(l+lst-1)%n+1;
r=(r+lst-1)%n+1;
if(l>r)
swap(l,r);
cout<<(lst=id[query(l,r)])<<'\n';
}
}