|
| 1 | +```cpp |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | +using ll = long long; |
| 5 | + |
| 6 | +int N, Q; |
| 7 | +vector<pair<int, int>> infos; |
| 8 | +int arr[300001]{}, idx[300001]{}, cnt[300001]{}, ans[300000]{}; |
| 9 | +ll sum[300001]{}; |
| 10 | +vector<tuple<int, int, int>> queries; |
| 11 | + |
| 12 | +void upt(int x, int v) { |
| 13 | + for (; x <= 300000; x += x & -x) { |
| 14 | + sum[x] += v; |
| 15 | + cnt[x]++; |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +pair<ll, int> find(int x) { |
| 20 | + pair<ll, int> ret = { 0,0 }; |
| 21 | + for (; x > 0; x -= x & -x) { |
| 22 | + ret.first += sum[x]; |
| 23 | + ret.second += cnt[x]; |
| 24 | + } |
| 25 | + return ret; |
| 26 | +} |
| 27 | + |
| 28 | +int main() { |
| 29 | + cin.tie(0)->sync_with_stdio(0); |
| 30 | + |
| 31 | + cin >> N >> Q; |
| 32 | + for (int i = 1; i <= N; i++) { |
| 33 | + cin >> arr[i]; |
| 34 | + infos.emplace_back(arr[i], i); |
| 35 | + } |
| 36 | + |
| 37 | + sort(infos.begin(), infos.end()); |
| 38 | + for (int i = 0; i < N; i++) { |
| 39 | + auto [v, x] = infos[i]; |
| 40 | + idx[x] = i + 1; |
| 41 | + } |
| 42 | + |
| 43 | + queries.resize(Q); |
| 44 | + for (int i = 0; i < Q; i++) { |
| 45 | + auto& [X, P, x] = queries[i]; |
| 46 | + cin >> X >> P; |
| 47 | + x = i; |
| 48 | + } |
| 49 | + |
| 50 | + sort(queries.begin(), queries.end()); |
| 51 | + |
| 52 | + int pos = 0; |
| 53 | + for (auto [X, P, x] : queries) { |
| 54 | + while (pos < X) { |
| 55 | + pos++; |
| 56 | + upt(idx[pos], arr[pos]); |
| 57 | + } |
| 58 | + pair<ll, int> ri = find(N); |
| 59 | + if (P > ri.first) { |
| 60 | + ans[x] = -1; |
| 61 | + continue; |
| 62 | + } |
| 63 | + int s = 0, e = N - 1, m = (s + e + 1) >> 1; |
| 64 | + while (s < e) { |
| 65 | + pair<ll, int> le = find(m); |
| 66 | + if (ri.first - le.first >= P) s = m; |
| 67 | + else e = m - 1; |
| 68 | + m = (s + e + 1) >> 1; |
| 69 | + } |
| 70 | + ans[x] = ri.second - find(m).second; |
| 71 | + } |
| 72 | + |
| 73 | + for (int i = 0; i < Q; i++) cout << ans[i] << '\n'; |
| 74 | + |
| 75 | +} |
| 76 | +``` |
0 commit comments