Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <string>
- struct Node
- {
- int prefixes;
- Node** ch;
- Node()
- {
- prefixes = 0;
- ch = new Node*[26];
- for (int i = 0; i < 26; i++)
- {
- ch[i] = nullptr;
- }
- }
- };
- struct Trie
- {
- Node* root;
- Trie()
- {
- this->root = new Node;
- }
- void add(char* str)
- {
- int i = 0;
- Node* c = this->root;
- while (str[i] != 0)
- {
- if (c->ch[str[i] - 'a'] == nullptr)
- {
- c->ch[str[i] - 'a'] = new Node;
- }
- c->prefixes++;
- c = c->ch[str[i] - 'a'];
- i++;
- }
- c->prefixes++;
- }
- int find(char* str)
- {
- int i = 0;
- Node* c = this->root;
- while (str[i] != 0 && c->ch[str[i] - 'a'] != nullptr)
- {
- c = c->ch[str[i] - 'a'];
- i++;
- }
- if (str[i] != 0)
- {
- return 0;
- }
- return c->prefixes;
- }
- };
- int main()
- {
- std::ios_base::sync_with_stdio(false);
- std::cin.tie(nullptr);
- int n, q;
- std::cin >> n >> q;
- Trie t;
- char s[21];
- for (int i = 0; i < n; i++)
- {
- std::cin >> s;
- t.add(s);
- }
- for (int i = 0; i < q; i++)
- {
- std::cin >> s;
- std::cout << t.find(s) << '\n';
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement