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
| #include<bits/stdc++.h> using namespace std; template <class T> inline void read(T &res) { res = 0; bool flag = 0; char c = getchar(); while('0' > c || c > '9') { if(c == '-') flag = 1; c = getchar();} while('0' <= c && c <= '9') res = (res << 3) + (res << 1) + (c ^ 48), c = getchar(); if(flag) res = -res; } const int N = 4e4 + 5; int n, m; int last, ans, res; int s[40][40], a[N], seg[40][40][N]; int len, limit; int pos[N], l[N], r[N], num[N]; vector<int> d; inline void ask(int st, int ed, int &hh, int &tt) { for(int i = 1;i <= len;i ++) if(st <= l[i] && r[i] <= ed) { hh = i; break; } for(int i = len;i >= 1;i --) if(st <= l[i] && r[i] <= ed) { tt = i; break; } } int main() { read(n), read(m); for(int i = 1;i <= n;i ++) read(a[i]), d.push_back(a[i]); sort(d.begin(), d.end()); d.erase(unique(d.begin(), d.end()), d.end()); for(int i = 1;i <= n;i ++) a[i] = lower_bound(d.begin(), d.end(), a[i]) - d.begin() + 1; limit = n / (cbrt(n) + 1); for(int i = 1;i <= n;i ++) { if(i > len * limit) r[len] = i - 1, len ++, l[len] = i; pos[i] = len; } r[len] = n; for(int i = 1;i <= len;i ++) { for(int j = i, ans;j <= len;j ++) { ans = 0; for(int k = l[i];k <= r[j];k ++) { seg[i][j][a[k]] ++; if(seg[i][j][a[k]] == ans) s[i][j] = min(s[i][j], a[k]); if(seg[i][j][a[k]] > ans) ans = seg[i][j][a[k]], s[i][j] = a[k]; } } } int st, ed, hh, tt; while(m --) { read(st), read(ed); st = (st + last - 1) % n + 1, ed = (ed + last - 1) % n + 1; if(st > ed) swap(st, ed); hh = tt = 0; ans = res = 0; ask(st, ed, hh, tt); if(hh) for(int i = st;i < l[hh];i ++) num[a[i]] ++; if(tt) for(int i = r[tt] + 1;i <= ed;i ++) num[a[i]] ++; if(!hh && !tt) for(int i = st;i <= ed;i ++) num[a[i]] ++; ans = num[s[hh][tt]] + seg[hh][tt][s[hh][tt]], res = s[hh][tt]; if(hh && tt) { for(int i = st;i < l[hh];i ++) { if(num[a[i]] + seg[hh][tt][a[i]] == ans) res = min(res, a[i]); if(num[a[i]] + seg[hh][tt][a[i]] > ans) ans = num[a[i]] + seg[hh][tt][a[i]], res = a[i]; } for(int i = r[tt] + 1;i <= ed;i ++) { if(num[a[i]] + seg[hh][tt][a[i]] == ans) res = min(res, a[i]); if(num[a[i]] + seg[hh][tt][a[i]] > ans) ans = num[a[i]] + seg[hh][tt][a[i]], res = a[i]; } } else { for(int i = st;i <= ed;i ++) { if(num[a[i]] == ans) res = min(res, a[i]); if(num[a[i]] > ans) ans = num[a[i]], res = a[i]; } } last = d[res - 1]; printf("%d\n", last); if(hh) for(int i = st;i < l[hh];i ++) num[a[i]] = 0; if(tt) for(int i = r[tt] + 1;i <= ed;i ++) num[a[i]] = 0; if(!hh && !tt) for(int i = st;i <= ed;i ++) num[a[i]] = 0; } return 0; }
|