int N, Q, S, K; int D[101111]; int log[101111]; int go[101111]; int f[101111][20]; map<int, int> pos;
constint inf = 999999999;
voidPrepare(){ for (int i = 0; i <= N; i++) pos[D[i]] = i; for (int i = 0; i <= N; i++) f[i][0] = D[i]; for (int j = 1; j < 20; j++) { for (int i = 0; i <= N; i++) { int t = i + (1 << (j - 1)); if (t < N) f[i][j] = max(f[i][j - 1], f[t][j - 1]); } } log[1] = 0; for (int i = 2; i <= N + 2; i++) { if (i == (i & -i)) log[i] = log[i - 1] + 1; else log[i] = log[i - 1]; } stack<int> s; s.push(N); for (int i = N - 1; i >= 0; i--) { while (D[i] > D[s.top()]) s.pop(); go[i] = s.top(); s.push(i); } }
intGetmax(int l, int r){ int len = r - l + 1; int t = log[len]; returnmax(f[l][t], f[r - (1 << t) + 1][t]); }
intCalc(int p){ int x = Getmax(p, S - 1); int a = pos[x]; int b = go[a]; return b - p; }
intWork(){ if (K == 1) return S; int l = 1, r = S - 1, res = 0; while (l <= r) { int mid = (l + r) / 2; int num = Calc(mid); if (num + 1 >= K) { res = mid; l = mid + 1; } else r = mid - 1; } int num = Calc(res); if (num + 1 == K) return res; elsereturn res + K; }
voidAAAAA(){ int T; cin >> T; for (int tt = 1; tt <= T; tt++) { cin >> N >> Q; for (int i = 1; i <= N - 1; i++) cin >> D[i]; D[0] = inf; D[N] = inf; Prepare(); printf("Case #%d: ", tt); while (Q--) { cin >> S >> K; printf("%d ", Work()); } printf("\n"); } }