Raslboyy

3871

Oct 15th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <string>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. class Node {
  10. public:
  11.     char let;
  12.     Node* way[26]{ nullptr };
  13.     Node* pr;
  14.     int count = 0;
  15.     Node (char let, Node* pr) : let(let), pr(pr){}
  16. };
  17.  
  18. class MBor {
  19. public:
  20.  
  21.     void Add(string str) {
  22.         Node* cur = root;
  23.         for (char ch : str) {
  24.             if (cur->way[ch - 'a'] != nullptr)
  25.                 cur = cur->way[ch - 'a'];
  26.             else {
  27.                 cur->way[ch - 'a'] = new Node(ch, cur);
  28.                 cur = cur->way[ch - 'a'];
  29.             }
  30.         }
  31.         cur->count++;
  32.     }
  33.     int get(string str) {
  34.         Node* cur = root;
  35.         for (char ch : str) {
  36.             if (cur->way[ch - 'a'] != nullptr) {
  37.                 cur = cur->way[ch - 'a'];
  38.             }
  39.             else return 0;
  40.         }
  41.         reverse(str.begin(), str.end());
  42.         return dfs(cur, str);
  43.     }
  44. private:
  45.     Node* root = new Node('-', nullptr);
  46.     int dfs(Node* cur, string str) {
  47.         int res = 0;
  48.         if (cur->count != 0 && check(cur, str)) {
  49.             res += cur->count;
  50.         }
  51.         for (auto v : cur->way) {
  52.             if (v != nullptr)
  53.                 res += dfs(v, str);
  54.         }
  55.         return res;
  56.     }
  57.     bool check(Node* v, string str) {
  58.         Node* cur = v;
  59.         for (char ch : str) {
  60.             if (cur->let == ch)
  61.                 cur = cur->pr;
  62.             else return 0;
  63.         }
  64.         return 1;
  65.     }
  66. };
  67.  
  68. int main() {
  69.     ifstream fin("input.txt");
  70.     ofstream fout("output.txt");
  71.  
  72.     int n, m;
  73.     fin >> n;
  74.     MBor br;
  75.     string str;
  76.     for (int i = 0; i < n; i++) {
  77.         fin >> str;
  78.         br.Add(str);
  79.     }
  80.     fin >> m;
  81.     for (int i = 0; i < m; i++) {
  82.         fin >> str;
  83.         fout << br.get(str) << endl;
  84.     }
  85.  
  86.     fin.close();
  87.     fout.close();
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment