You are given queries of two types:
- : Append value into an array.
- : You are required to print the minimum XOR of with the current array.
You have to make a new array whose element is current_array[i]. Then sort it and print the element.
Example:
Input: q = 8, queries = {{1, 5}, {1, 3}, {1, 2}, {1, 9}, {2, 8, 3}, {1, 89}, {1, 56}, {2, 85, 5}}
Output:
11 92
Approach:
C++
#include <bits/stdc++.h>using namespace std;//structure of the triestruct Trienode{Trienode *left;Trienode *right;int below = 0;};//function to insert the data into//the trievoid insert(Trienode *head, long long element){Trienode *curr = head;for (long long i = 63; i >= 0; i--){long long b = (element >> i) & 1;curr->below++;//if zero go for left sideif (b == 0){//if left does not exit//then create new node for leftif (!curr->left){curr->left = new Trienode();}//move to left of current nodecurr = curr->left;}//if not zero then go to//right sideelse{//if right does not exist//create new node for rightif (!curr->right){curr->right = new Trienode();}//move right of current nodecurr = curr->right;}}//update belowcurr->below++;}long long query(Trienode *head, long long x, long long k){Trienode *curr = head;long long ans = 0;for (long long i = 63; i >= 0; i--){long long b = (x >> i) & 1;long long t = (1LL << i);long long res = 0;//if zero then go to left sizeif (b == 0){//if current's left existif (curr->left){res = curr->left->below;}if (res >= k){curr = curr->left;}//now move to right sideelse{ans += t;k -= res;if (!curr->right){curr->right = new Trienode();}curr = curr->right;}}//if not zero then go to right sideelse{if (curr->right){res = curr->right->below;}if (res >= k){curr = curr->right;}else{ans += t;k -= res;if (!curr->left){curr->left = new Trienode();}curr = curr->left;}}}return ans;}int main(){Trienode *head = new Trienode();long long q = 8;vector<vector<long long>> queries = {{1, 5},{1, 3},{1, 2},{1, 9},{2, 8, 3},{1, 89},{1, 56},{2, 85, 5}};for (long long i = 0; i < q; i++){long long c = queries[i][0];if (c == 1){long long y = queries[i][1];insert(head, y);}else{long long x = queries[i][1];long long k = queries[i][2];cout << query(head, x, k) << "\n";}}return 0;}
No comments:
Post a Comment