Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <string>
- #include <algorithm>
- using namespace std;
- class Node {
- public:
- char let;
- Node* way[26]{ nullptr };
- Node* pr;
- int count = 0;
- Node (char let, Node* pr) : let(let), pr(pr){}
- };
- class MBor {
- public:
- void Add(string str) {
- Node* cur = root;
- for (char ch : str) {
- if (cur->way[ch - 'a'] != nullptr)
- cur = cur->way[ch - 'a'];
- else {
- cur->way[ch - 'a'] = new Node(ch, cur);
- cur = cur->way[ch - 'a'];
- }
- }
- cur->count++;
- }
- int get(string str) {
- Node* cur = root;
- for (char ch : str) {
- if (cur->way[ch - 'a'] != nullptr) {
- cur = cur->way[ch - 'a'];
- }
- else return 0;
- }
- reverse(str.begin(), str.end());
- return dfs(cur, str);
- }
- private:
- Node* root = new Node('-', nullptr);
- int dfs(Node* cur, string str) {
- int res = 0;
- if (cur->count != 0 && check(cur, str)) {
- res += cur->count;
- }
- for (auto v : cur->way) {
- if (v != nullptr)
- res += dfs(v, str);
- }
- return res;
- }
- bool check(Node* v, string str) {
- Node* cur = v;
- for (char ch : str) {
- if (cur->let == ch)
- cur = cur->pr;
- else return 0;
- }
- return 1;
- }
- };
- int main() {
- ifstream fin("input.txt");
- ofstream fout("output.txt");
- int n, m;
- fin >> n;
- MBor br;
- string str;
- for (int i = 0; i < n; i++) {
- fin >> str;
- br.Add(str);
- }
- fin >> m;
- for (int i = 0; i < m; i++) {
- fin >> str;
- fout << br.get(str) << endl;
- }
- fin.close();
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment