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
| const int maxn = 40000 + 5; const int T = 800 + 5; int f[T][T]; int n, m, t; int a[maxn], b[maxn]; int ct[maxn]; vector<int> show[maxn];
map<int, int> loc;
class Seg { public: int l, r; };
Seg seg[maxn]; int pos[maxn];
void init() { Set(pos, 0); Set(f, 0); _for(i, 0, maxn) show[i].clear(); Set(ct, 0);
loc.clear(); }
void discrete() { sort(b + 1, b + 1 + n); int tot = unique(b + 1, b + 1 + n) - b - 1;
_rep(i, 1, n) { a[i] = lower_bound(b + 1, b + 1 + tot, a[i]) - b; show[a[i]].push_back(i); }
}
void split(const int len) { _rep(i, 1, t) { seg[i].l = (i - 1) * len + 1; seg[i].r = i * len; } if(seg[t].r < n) { t++; seg[t].l = seg[t - 1].r + 1; seg[t].r = n; }
_rep(i, 1, n) { _rep(j, seg[i].l, seg[i].r) pos[j] = i; } }
inline void cal() { _rep(i, 1, t) { int ans = 0, cnt = 0; Set(ct, 0);
_rep(j, seg[i].l, n) { ct[a[j]]++; if(cnt < ct[a[j]] || (cnt == ct[a[j]] && a[j] < ans)) { cnt = ct[a[j]]; ans = a[j]; }
f[i][pos[j]] = ans; } } }
int count(int x, int l, int r) { return upper_bound(show[x].begin(), show[x].end(), r) - lower_bound(show[x].begin(), show[x].end(), l); }
void update(int x, int l, int r, int &ans, int &cnt) { int c = count(x, l, r); if(c > cnt || (c == cnt && x < ans)) { cnt = c; ans = x; } }
int ask(int l, int r) { int p = pos[l], q = pos[r]; int ans = 0, cnt = 0; if(p == q) { _rep(i, l, r) update(a[i], l, r, ans, cnt); return b[ans]; }
int x = 0, y = 0; if(p + 1 <= q - 1) { x = p + 1; y = q - 1; }
_rep(i, l, seg[p].r) update(a[i], l, r, ans, cnt); _rep(i, seg[q].l, r) update(a[i], l, r, ans, cnt); if(f[x][y]) update(f[x][y], l, r, ans, cnt);
//debug(ans); return b[ans]; }
int main() { freopen("input.txt", "r", stdin); init(); cin >> n >> m; _rep(i, 1, n) scanf("%d", &a[i]); Cpy(b, a);
// == discrete == discrete(); // == discrete finished ==
// == part == t = sqrt(n * log(n) / log(2)); int len = t ? n / t : n;
// == split == split(len); // == split finished ==
// == calculate f() == cal(); // == f() finished==
// == main algorithm == int res = 0; while (m--) { int l, r; scanf("%d%d", &l, &r);
l = (l + res - 1) % n + 1; r = (r + res - 1) % n + 1; //debug(l), debug(r);
if(l > r) swap(l, r); res = ask(l, r); printf("%d\n", res); }
}
|