From d08421fad2eb6b228e6ee8dd28a79c660146724c Mon Sep 17 00:00:00 2001 From: Ren Baoshuo Date: Sun, 12 Sep 2021 15:50:07 +0800 Subject: [PATCH] =?UTF-8?q?143.=20=E6=9C=80=E5=A4=A7=E5=BC=82=E6=88=96?= =?UTF-8?q?=E5=AF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.acwing.com/problem/content/submission/code_detail/7682567/ --- AcWing/143/143.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 AcWing/143/143.cpp diff --git a/AcWing/143/143.cpp b/AcWing/143/143.cpp new file mode 100644 index 00000000..c647a2b9 --- /dev/null +++ b/AcWing/143/143.cpp @@ -0,0 +1,55 @@ +#include + +using namespace std; + +int n, a[100005], ans; + +struct node { + int val; + node* next[2]; + + ~node() { + for (auto i : next) { + delete i; + } + } +}; + +void insert(node* root, int x, int b) { + if (!x) { + root->val++; + return; + } + if (root->next[(x >> b) & 1] == nullptr) root->next[(x >> b) & 1] = new node(); + insert(root->next[(x >> b) & 1], x - (((x >> b) & 1) << b), b - 1); +} + +int search(node* root, int x) { + int res = 0; + node* p = root; + for (int i = 30; i >= 0; i--) { + if (p == nullptr) break; + if (p->next[!((x >> i) & 1)] != nullptr) { + res += 1 << i; + p = p->next[!((x >> i) & 1)]; + } else { + p = p->next[(x >> i) & 1]; + } + } + return res; +} + +int main() { + node* root = new node(); + cin >> n; + for (int i = 0; i < n; i++) { + cin >> a[i]; + insert(root, a[i], 30); + } + for (int i = 0; i < n; i++) { + ans = max(ans, search(root, a[i])); + } + cout << ans << endl; + delete root; + return 0; +}