From 16a05f1a38e4d420dbf792686f3a8e71cde06112 Mon Sep 17 00:00:00 2001 From: Ren Baoshuo Date: Sun, 12 Sep 2021 14:06:27 +0800 Subject: [PATCH] =?UTF-8?q?835.=20Trie=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=BB=9F?= =?UTF-8?q?=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.acwing.com/problem/content/submission/code_detail/7680320/ --- AcWing/835/835.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 AcWing/835/835.cpp diff --git a/AcWing/835/835.cpp b/AcWing/835/835.cpp new file mode 100644 index 00000000..aabe369c --- /dev/null +++ b/AcWing/835/835.cpp @@ -0,0 +1,46 @@ +#include + +using namespace std; + +int n; +char op; +string s; + +struct node { + int val; + node* next[30]; + + ~node() { + for (auto i : next) { + delete i; + } + } +}; + +void insert(node* root, string s) { + if (s.empty()) { + root->val++; + return; + } + if (root->next[s[0] - 'a'] == nullptr) root->next[s[0] - 'a'] = new node(); + insert(root->next[s[0] - 'a'], s.substr(1)); +} + +int query(node* root, string s) { + return s.empty() ? root->val : (root->next[s[0] - 'a'] == nullptr ? 0 : query(root->next[s[0] - 'a'], s.substr(1))); +} + +int main() { + node* root = new node(); + cin >> n; + for (int i = 0; i < n; i++) { + cin >> op >> s; + if (op == 'I') { + insert(root, s); + } else { + cout << query(root, s) << endl; + } + } + delete root; + return 0; +}