From aff545a59f0c5d2e46c07466f2d6a810f24c20b3 Mon Sep 17 00:00:00 2001 From: DarianTr Date: Mon, 17 Jun 2024 10:31:00 +0200 Subject: [PATCH] xor --- .../Dynamic_Range_Sum_Queries.cpp | 8 +-- .../Range_Queries/Range_XOR_Query.cpp | 60 +++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 CSES - CSES Problem Set/Range_Queries/Range_XOR_Query.cpp diff --git a/CSES - CSES Problem Set/Range_Queries/Dynamic_Range_Sum_Queries.cpp b/CSES - CSES Problem Set/Range_Queries/Dynamic_Range_Sum_Queries.cpp index 5dcf578..1a26d1d 100644 --- a/CSES - CSES Problem Set/Range_Queries/Dynamic_Range_Sum_Queries.cpp +++ b/CSES - CSES Problem Set/Range_Queries/Dynamic_Range_Sum_Queries.cpp @@ -10,7 +10,7 @@ vector construct(vector &input) { output[input.size() + i] = input[i]; } for (int i = input.size() - 1; i > 0; i--) { - output[i] = output[2*i] + output[2*i + 1]; + output[i] = (output[2*i] ^ output[2*i + 1]); } return output; } @@ -20,7 +20,7 @@ void update(int k, ll x, int n, vector &tree) { tree[k] = x; k /= 2; for (; k >= 1; k /= 2) { - tree[k] = tree[2*k + 1] + tree[2*k]; + tree[k] = (tree[2*k + 1] ^ tree[2*k]); } } @@ -30,11 +30,11 @@ ll query(int a, int b, int n, vector &tree) { ll s = 0; while (a <= b) { if (a % 2 == 1) { - s += tree[a]; + s ^= tree[a]; a++; } if (b % 2 == 0) { - s += tree[b]; + s ^= tree[b]; b--; } a /= 2; b /= 2; diff --git a/CSES - CSES Problem Set/Range_Queries/Range_XOR_Query.cpp b/CSES - CSES Problem Set/Range_Queries/Range_XOR_Query.cpp new file mode 100644 index 0000000..23b139a --- /dev/null +++ b/CSES - CSES Problem Set/Range_Queries/Range_XOR_Query.cpp @@ -0,0 +1,60 @@ +// +// Created by darian on 17.06.24. +// + +#include + +using namespace std; +using ll = long long; + +void update(int x, ll u, vector &tree, int n) { + x--; + x += n; + tree[x] = u; + x /= 2; + for (; x >= 1; x /= 2) { + tree[x] = tree[2*x] ^ tree[2*x + 1]; + } +} + +vector construct(vector &input) { + int n = input.size(); + vector output(2 * n); + for (int i = n; i < 2 * n; i++) { + output[i] = input[i - n]; + } + for (int i = n - 1; i >= 1; i --) { + output[i] = output[2 * i] ^ output[2 * i + 1]; + } + return output; +} + +ll query(int a, int b, vector &tree, int n) { + a--; b--; + a += n; b += n; + ll s = 0; + while (a <= b) { + if (a % 2 == 1) { + s ^= tree[a]; + a++; + } + if (b % 2 == 0) { + s ^= tree[b]; + b--; + } + a /= 2; b /= 2; + } + return s; +} + +int main() { + int n; cin >> n; + int q; cin >> q; + vector input(n); + for (int i{}; i < n; i++) cin >> input[i]; + auto seg = construct(input); + for (int i{}; i < q; i++) { + int a, b; cin >> a >> b; + cout << query(a, b, seg, n) << endl; + } +} \ No newline at end of file