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
| #include <bits/stdc++.h> #define int long long using namespace std;
const int N = 2e5 + 10, M = N * 30; int son[M][2], idx; vector<vector<int>> indices(M);
void insert(int x, int id) { int p = 0; indices[p].push_back(id); for(int i = 29; i >= 0; i--) { int u = (x >> i) & 1; if(!son[p][u]) son[p][u] = ++idx; p = son[p][u]; indices[p].push_back(id); } }
bool has_index_in_range(int p, int l, int r) { auto& vec = indices[p]; auto it = lower_bound(vec.begin(), vec.end(), l); return it != vec.end() && *it <= r; }
int query(int l, int r, int x) { int p = 0, res = 0; for(int i = 29; i >= 0; i--) { int u = (x >> i) & 1; if(son[p][!u] && has_index_in_range(son[p][!u], l, r)) { p = son[p][!u]; res = res * 2 + 1; } else if(son[p][u] && has_index_in_range(son[p][u], l, r)) { p = son[p][u]; res = res * 2; } else { return -1; } } return res; }
void solve() { memset(son, 0, sizeof son); for(auto& v : indices) v.clear(); idx = 0; int n, q; cin >> n >> q; vector<int> a(n); for(int i = 0; i < n; i++) { cin >> a[i]; insert(a[i], i + 1); } for(auto& v : indices) { sort(v.begin(), v.end()); } while(q--) { int l, r, x; cin >> l >> r >> x; cout << query(l, r, x) << '\n'; } }
signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while(t--) solve(); return 0; }
|