Given an array of n integers, your task is to process q queries of the form: what is the xor sum of values in the range [a,b]?
Example:
Input: n = 8, q = 4, a = {3, 2, 4, 5, 1, 1, 5, 3}, queries = {{2, 4}, {5, 6}, {1, 8}, {3, 3}}
Output:
3 0 6 4
Approach:
C++
#include <bits/stdc++.h>using namespace std;long long arr[1000001];long long tree[4010001];void build(long long node, long long start, long long end){if (start == end){tree[node] = arr[start];return;}long long mid = (start + end) / 2;build(2 * node, start, mid);build(2 * node + 1, mid + 1, end);tree[node] = tree[2 * node] ^ tree[2 * node + 1];}long long query(long long node, long long start,long long end, long long l, long long r){if (r < start || l > end)return 0;if (l <= start && r >= end)return tree[node];long long mid = (start + end) / 2;long long p1 = query(2 * node, start, mid, l, r);long long p2 = query(2 * node + 1, mid + 1, end, l, r);return p1 ^ p2;}void update(long long node, long long start,long long end, long long index, long long val){if (start == end){tree[node] = arr[start];return;}int mid = (start + end) / 2;if (index <= mid)update(2 * node, start, mid, index, val);else{update(2 * node + 1, mid + 1, end, index, val);}tree[node] = tree[2 * node] ^ tree[2 * node + 1];}int main(){long long n = 8, q = 4;vector<long long> a = {3, 2, 4, 5, 1, 1, 5, 3};vector<vector<long long>> queries = {{2, 4},{5, 6},{1, 8},{3, 3}};for (long long i = 1; i <= n; i++)arr[i] = a[i - 1];build(1, 1, n);for (long long i = 0; i < q; i++){long long l = queries[i][0];long long r = queries[i][1];cout << query(1, 1, n, l, r) << "\n";}return 0;}
No comments:
Post a Comment