#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<vector> using namespace std; int maxn,m,n,tot,T,mode[1000][1000],last[40010], a[40010],ord[40010],L[1000],R[1000],cnt[40010]; vector<int> plc[40010]; vector<int>::iterator i1,i2; int main() { int i,j,k,p,q,x,y,z,K,ans,l,r,ll,rr,ans_cnt,xx; scanf("%d%d",&n,&m); for (i=1;i<=n;i++) scanf("%d",&a[i]),ord[i]=a[i]; sort(ord+1,ord+n+1); maxn=unique(ord+1,ord+n+1)-ord-1; for (i=1;i<=n;i++) a[i]=lower_bound(ord+1,ord+maxn+1,a[i])-ord; tot=sqrt(n*log(n)/log(2)); T=n/tot; for (i=1;i<=tot;i++) { L[i]=R[i-1]+1; if (i==tot) R[i]=n; else R[i]=L[i]+T-1; } for (i=1;i<=tot;i++) { memset(cnt,0,sizeof(cnt)); for (j=i;j<=tot;j++) { mode[i][j]=mode[i][j-1]; for (k=L[j];k<=R[j];k++) { cnt[a[k]]++; if (cnt[a[k]]>cnt[mode[i][j]]|| (cnt[a[k]]==cnt[mode[i][j]]&&a[k]<mode[i][j])) mode[i][j]=a[k]; } } } for (i=1;i<=n;i++) plc[a[i]].push_back(i); ans=0; for (K=1;K<=m;K++) { scanf("%d%d",&l,&r); l=(l+ans-1)%n+1; r=(r+ans-1)%n+1; if (l>r) swap(l,r); ll=1; while (ll<=tot&&L[ll]<l) ll++; rr=tot; while (rr&&R[rr]>r) rr--; if (ll>rr) { ans=0; ans_cnt=-1; for (i=l;i<=r;i++) { i1=lower_bound(plc[a[i]].begin(),plc[a[i]].end(),l); i2=upper_bound(plc[a[i]].begin(),plc[a[i]].end(),r); xx=i2-i1; if (xx>ans_cnt||(xx==ans_cnt&&a[i]<ans)) { ans=a[i]; ans_cnt=xx; } } ans=ord[ans]; printf("%d\n",ans); continue; } ans=mode[ll][rr]; i1=lower_bound(plc[ans].begin(),plc[ans].end(),l); i2=upper_bound(plc[ans].begin(),plc[ans].end(),r); ans_cnt=i2-i1; for (i=l;i<L[ll];i++) { i1=lower_bound(plc[a[i]].begin(),plc[a[i]].end(),l); i2=upper_bound(plc[a[i]].begin(),plc[a[i]].end(),r); xx=i2-i1; if (xx>ans_cnt||(xx==ans_cnt&&a[i]<ans)) { ans=a[i]; ans_cnt=xx; } } for (i=R[rr]+1;i<=r;i++) { i1=lower_bound(plc[a[i]].begin(),plc[a[i]].end(),l); i2=upper_bound(plc[a[i]].begin(),plc[a[i]].end(),r); xx=i2-i1; if (xx>ans_cnt||(xx==ans_cnt&&a[i]<ans)) { ans=a[i]; ans_cnt=xx; } } ans=ord[ans]; printf("%d\n",ans); } }
|