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
| #include <cstdio> #include <cmath> #include <vector> #include <algorithm> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') (c == '-') && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; (flag) && (x = ~x + 1); } const int N = 4e4 + 10, M = 210; int n, m, len, w[N], s[M][N], p[M][M], cnt[N]; int query(int l, int r) { if (r / len - l / len < 2) { int t = -1; for (int i = l; i <= r; i++) { cnt[w[i]]++; if (t == -1 || cnt[w[i]] > cnt[t] || (cnt[w[i]] == cnt[t] && w[i] < t)) t = w[i]; } for (int i = l; i <= r; i++) cnt[w[i]]--; return t; } int t = p[l / len + 1][r / len - 1], mx = s[r / len - 1][t] - s[l / len][t]; for (int i = l; i < l / len * len + len; i++) { cnt[w[i]]++; int v = cnt[w[i]] + s[r / len - 1][w[i]] - s[l / len][w[i]]; if (v > mx || (v == mx && w[i] < t)) { t = w[i]; mx = v; } } for (int i = r / len * len; i <= r; i++) { cnt[w[i]]++; int v = cnt[w[i]] + s[r / len - 1][w[i]] - s[l / len][w[i]]; if (v > mx || (v == mx && w[i] < t)) { t = w[i]; mx = v; } } for (int i = l; i < l / len * len + len; i++) cnt[w[i]]--; for (int i = r / len * len; i <= r; i++) cnt[w[i]]--; return t; } int main() { read(n), read(m); len = sqrt(n); vector<int> ws; for (int i = 0; i < n; i++) { read(w[i]); ws.push_back(w[i]); } sort(ws.begin(), ws.end()); ws.erase(unique(ws.begin(), ws.end()), ws.end()); for (int i = 0; i < n; i++) w[i] = lower_bound(ws.begin(), ws.end(), w[i]) - ws.begin(); for (int i = 0; i < n; i++) s[i / len][w[i]]++; for (int i = 1; i <= (n - 1) / len; i++) for (int j = 0; j < n; j++) s[i][j] += s[i - 1][j]; for (int i = 0; i <= (n - 1) / len; i++) { for (int j = i, t = -1; j <= (n - 1) / len; j++) { for (int k = j * len; k < min(n, j * len + len); k++) { cnt[w[k]]++; if (t == -1 || cnt[w[k]] > cnt[t] || (cnt[w[k]] == cnt[t] && w[k] < t)) t = w[k]; } p[i][j] = t; } for (int j = 0; j < n; j++) cnt[j] = 0; } for (int l, r, last = 0; m; m--) { read(l), read(r); l = (l + last - 1) % n, r = (r + last - 1) % n; if (l > r) swap(l, r); printf("%d\n", last = ws[query(l, r)]); } return 0; }
|