#include #include using namespace std; using namespace atcoder; struct node { int l, r, val, sum; node(int s = 0) { l = 0; r = s; val = 0; sum = s; } }; node e() { return node(); } node op(node a, node b) { node ans; ans.l = min(a.l, a.sum + b.l); ans.r = max(a.r, a.sum + b.r); ans.sum = a.sum + b.sum; ans.val = min({a.val + b.sum, b.val + a.sum, ans.sum - (b.r + a.sum) + a.l}); return ans; } ostream& operator<<(ostream &out, node x) { return out << "(" << x.l << ", " << x.r << ", " << x.sum << ", " << x.val << ")"; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n, q; cin >> n >> q; vector a(n); vector> pos(n); for (int i = 0; i < n; i++) { cin >> a[i]; a[i]--; pos[a[i]].push_back(i); } vector> que(q), rng(q); vector> xd(n); auto set_range = [&](int i, int l, int r) { rng[i] = {l, r}; if (l + 1 < r) { xd[(l + r) / 2].push_back(i); } }; for (int i = 0; i < q; i++) { int l, r; cin >> l >> r; l--; if (l + 1 == r) { set_range(i, a[l], a[l]); } else { que[i] = {l, r}; set_range(i, 0, n); } } while (true) { vector> cur(n); swap(cur, xd); bool ok = false; segtree seg(n); for (int i = 0; i < n; i++) { seg.set(i, node(1)); } for (int m = 0; m < n; m++) { for (int v : pos[m]) { seg.set(v, node(-1)); } for (int ind : cur[m]) { ok = true; auto [l, r] = que[ind]; node cc = seg.prod(l, r); auto [rl, rr] = rng[ind]; // for (int i = 0; i < n; i++) { // cerr << seg.get(i) << '\n'; // } // cerr << m + 1 << " " << l << " " << r << ": " << cc << endl; (cc.val + 1 >= 0 ? rl : rr) = m; set_range(ind, rl, rr); } } if (!ok) { break; } } for (int i = 0; i < q; i++) { cout << rng[i].second + 1 << '\n'; } }