wjh2022 @ 2024-02-04 17:01:11
#include<bits/stdc++.h>
using namespace std;
int n,m,B,x,d[100005],a[100005],b[100005],dui[100005],pos[100005],s[1005][1005],f[1005][1005],l[1005],r[1005],pre[205][40005];
bool vis[100005];
//b是离散前序列,a是离散后,d是离散后每个出现几次,dui是a的序号对应到b上,s是i块到j块的最小众数,f众数是出现次数 ,pre是前i个块内j出现次数
struct kkk{
int l,r;
}q[100005];
vector<int>mp;
void init(){
mp.clear();
for(int i=1;i<=n;i++)mp.push_back(b[i]);
sort(mp.begin(),mp.end());
mp.erase(unique(mp.begin(),mp.end()),mp.end());
for(int i=1;i<=n;i++)a[i]=lower_bound(mp.begin(),mp.end(),b[i])-mp.begin()+1;
}
int main(){
cin>>n>>m;
B=sqrt(n);
for(int i=1;i<=n;i++)cin>>b[i];
init();
for(int i=1;i<=n;i++)dui[a[i]]=b[i];
for(int i=1;i<=n;i++){
pos[i]=(i-1)/B+1;
l[pos[i]]=(pos[i]-1)*B+1;
r[pos[i]]=pos[i]*B;
}
r[pos[n]]=n;
for(int i=1;i<=n;i++){
if(pos[i]!=pos[i-1]){
for(int j=1;j<=n;j++)pre[pos[i]][j]=pre[pos[i]-1][j];
}
pre[pos[i]][a[i]]++;
}
// for(int i=1;i<=pos[n];i++){
// for(int j=1;j<=n;j++)cout<<pre[i][j]<<" ";
// cout<<"\n";
// }
for(int i=1;i<=pos[n];i++){
for(int j=i;j<=pos[n];j++){
int tot=0,cnt=n+1;
for(int k=l[j];k<=r[j];k++){
d[a[k]]++;
if(d[a[k]]==tot){
cnt=min(cnt,a[k]);
}
if(d[a[k]]>tot){
tot=d[a[k]];
cnt=a[k];
}
}
s[i][j]=cnt;
f[i][j]=tot;
}
memset(d,0,sizeof(d));
}
// for(int i=1;i<=pos[n];i++){
// for(int j=i;j<=pos[n];j++)cout<<s[i][j]<<" ";
// cout<<endl;
// }
// for(int i=1;i<=pos[n];i++){
// for(int j=i;j<=pos[n];j++)cout<<f[i][j]<<" ";
// cout<<endl;
// }
for(int i=1;i<=m;i++){
cin>>q[i].l>>q[i].r;
q[i].l=(q[i].l+x-1)%n+1;
q[i].r=(q[i].r+x-1)%n+1;
if(q[i].l>q[i].r)swap(q[i].l,q[i].r);
if(pos[q[i].r]-pos[q[i].l]<=1){
int tot=0,cnt=n+1;
for(int j=q[i].l;j<=q[i].r;j++)d[a[j]]=0;
for(int j=q[i].l;j<=q[i].r;j++){
d[a[j]]++;
if(d[a[j]]==tot){
cnt=min(cnt,a[j]);
}
if(d[a[j]]>tot){
tot=d[a[j]];
cnt=a[j];
}
}
x=dui[cnt];
cout<<x<<"\n";
}
else {
int tot=0,cnt=n+1;
for(int j=q[i].l;j<=r[pos[q[i].l]];j++){
d[a[j]]=0;
vis[a[j]]=0;
}
for(int j=l[pos[q[i].r]];j<=q[i].r;j++){
d[a[j]]=0;
vis[a[j]]=0;
}
for(int j=q[i].l;j<=r[pos[q[i].l]];j++){
d[a[j]]++;
if(!vis[a[j]]){
vis[a[j]]=1;
d[a[j]]+=pre[pos[q[i].r]-1][a[j]]-pre[pos[q[i].l]][a[j]];
if(d[a[j]]==tot){
cnt=min(cnt,a[j]);
}
if(d[a[j]]>tot){
tot=d[a[j]];
cnt=a[j];
}
}
if(d[a[j]]==tot){
cnt=min(cnt,a[j]);
}
if(d[a[j]]>tot){
tot=d[a[j]];
cnt=a[j];
}
}
for(int j=l[pos[q[i].r]];j<=q[i].r;j++){
d[a[j]]++;
if(!vis[a[j]]){
vis[a[j]]=1;
d[a[j]]+=pre[pos[q[i].r]-1][a[j]]-pre[pos[q[i].l]][a[j]];
if(d[a[j]]==tot){
cnt=min(cnt,a[j]);
}
if(d[a[j]]>tot){
tot=d[a[j]];
cnt=a[j];
}
}
if(d[a[j]]==tot){
cnt=min(cnt,a[j]);
}
if(d[a[j]]>tot){
tot=d[a[j]];
cnt=a[j];
}
}
if(tot==f[q[i].l+1][q[i].r-1]){
x=dui[min(cnt,s[q[i].l+1][q[i].r-1])];
cout<<x;
}
else if(tot>f[q[i].l+1][q[i].r-1]){
x=dui[cnt];
cout<<x;
}
else {
x=dui[f[q[i].l+1][q[i].r-1]];
cout<<x;
}
cout<<"\n";
}
}
return 0;
}