1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| #include<bits/stdc++.h> using namespace std; typedef long long ll; inline int read() { int x=0,f=1; char ss=getchar(); while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();} while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();} return x*f; } inline void out(register int x) { if(x>=10) out(x/10); putchar(x%10+'0'); } const int maxn=40005,lim=205,inf=0x3f3f3f3f; int a[maxn],c[maxn],id=0,f[lim][lim]; int siz,num,belong[maxn]; struct block { int l,r; } b[lim]; map<int,int> QAQ; vector<int> pos[maxn]; int val[maxn]; void debug(int n) { printf("siz=%d,num=%d\n",siz,num); for(int i=1;i<=num;i++) { for(int j=i;j<=num;j++) { printf("f[%d][%d]=%d\n",i,j,f[i][j]); } } } void build(int n) { siz=sqrt(n); num=n/siz; if(n%siz) num++; for(int i=1;i<=num;i++) b[i].l=(i-1)*siz+1,b[i].r=i*siz; b[num].r=n; for(int i=1;i<=n;i++) belong[i]=(i-1)/siz+1;
for(int i=1;i<=n;i++) { if(QAQ[a[i]]==0) { QAQ[a[i]]=++id; val[id]=a[i];
} a[i]=QAQ[a[i]]; pos[a[i]].push_back(i); } for(int i=1;i<=belong[n];i++) { memset(c,0,sizeof(c)); int maxc=0,ans=0; for(int j=b[i].l;j<=n;j++) { c[a[j]]++; if(c[a[j]]>maxc||c[a[j]]==maxc&&val[a[j]]<val[ans]) { maxc=c[a[j]]; ans=a[j]; } f[i][belong[j]]=ans;
} }
} int querynum(int l,int r,int x) { return upper_bound(pos[x].begin(),pos[x].end(),r)-lower_bound(pos[x].begin(),pos[x].end(),l); } int query(int l,int r) { int ans=0,maxc=0; ans=f[belong[l]+1][belong[r]-1]; maxc=querynum(l,r,ans); if(belong[l]==belong[r]) {
for(int i=l;i<=r;i++) { int num=querynum(l,r,a[i]); if(num>maxc||num==maxc&&val[a[i]]<val[ans]) {
ans=a[i]; maxc=num; } } return val[ans]; }
for(int i=l;i<=b[belong[l]].r;i++) { int num=querynum(l,r,a[i]); if(num>maxc||num==maxc&&val[a[i]]<val[ans]) {
ans=a[i]; maxc=num; } } for(int i=b[belong[r]].l;i<=r;i++) { int num=querynum(l,r,a[i]); if(num>maxc||num==maxc&&val[a[i]]<val[ans]) { ans=a[i]; maxc=num; }
}
return val[ans]; } signed main() {
int n,m,ans=0;
n=read(),m=read(); for(int i=1;i<=n;i++) a[i]=read(); build(n); while(m--) { int l0,r0,l,r;
l0=read(),r0=read(); l=(l0+ans-1)%n+1; r=(r0+ans-1)%n+1; if(l>r) swap(l,r); ans=query(l,r); printf("%d\n",ans); } return 0; }
|