From a608ebd2c070fbb58a51c94ce7f523b67453fdd7 Mon Sep 17 00:00:00 2001 From: Ren Baoshuo Date: Sun, 3 Oct 2021 08:35:29 +0800 Subject: [PATCH] =?UTF-8?q?142.=20=E5=89=8D=E7=BC=80=E7=BB=9F=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/8017084/ --- AcWing/142/142.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 AcWing/142/142.cpp diff --git a/AcWing/142/142.cpp b/AcWing/142/142.cpp new file mode 100644 index 00000000..64eef625 --- /dev/null +++ b/AcWing/142/142.cpp @@ -0,0 +1,51 @@ +#include + +using namespace std; + +int n, m, ans; +string s; + +struct node { + int size; + node* next[26]; + + ~node() { + for (auto& i : next) { + delete i; + } + } +}; + +void insert(node* root, string s) { + if (s.empty()) { + root->size++; + 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) { + if (s.empty()) return root->size; + if (root->next[s[0] - 'a'] == nullptr) return 0; + return query(root->next[s[0] - 'a'], s.substr(1)); +} + +int main() { + node* root = new node(); + cin >> n >> m; + for (int i = 1; i <= n; i++) { + cin >> s; + insert(root, s); + } + for (int i = 1; i <= m; i++) { + ans = 0; + cin >> s; + for (int j = 1; j <= s.size(); j++) { + ans += query(root, s.substr(0, j)); + } + cout << ans << endl; + } + delete root; + return 0; +}