Advertisement
Goga21

Untitled

Sep 3rd, 2024
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. //#define int long long
  4.  
  5. using namespace std;
  6.  
  7. struct node{
  8.     node *next[26];
  9.     int cnt;
  10.  
  11.     node(){
  12.         for(int i = 0; i < 26; ++i){
  13.             next[i] = nullptr;
  14.         }
  15.         cnt = 0;
  16.     }
  17. };
  18.  
  19. node *root = new node();
  20.  
  21. void add(string& input){
  22.     node *curr = root;
  23.  
  24.     for(int i = 0; i < input.size(); ++i){
  25.         if(curr->next[input[i] - 'a'] == nullptr){
  26.             curr->next[input[i] - 'a'] = new node();
  27.         }
  28.  
  29.         curr = curr->next[input[i] - 'a'];
  30.         curr->cnt++;
  31.     }
  32.  
  33.     root->cnt++;
  34. }
  35.  
  36. int search(string &input){
  37.     int ans = 0;
  38.  
  39.     node *temp = root;
  40.     for(auto el : input){
  41.         ans += temp->cnt;
  42.         temp = temp->next[el - 'a'];
  43.     }
  44.  
  45.     return ans;
  46. }
  47.  
  48. int cnt(const string &s){
  49.     int ans = root->cnt;
  50.     node *temp = root;
  51.  
  52.  
  53.     for(int i = 0; i < s.size(); ++i){
  54.         if(temp->next[s[i] - 'a'] == nullptr){
  55.             return ans;
  56.         }else{
  57.             ans += temp->cnt;
  58.             temp = temp->next[s[i] - 'a'];
  59.         }
  60.     }
  61.     return ans;
  62. }
  63.  
  64. signed main() {
  65.     ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
  66.     int n, m;
  67.     cin >> n;
  68.  
  69.     vector<string> v(n);
  70.     unordered_map<string, int> input;
  71.  
  72.     for(int i = 0; i < n; ++i) cin >> v[i];
  73.  
  74.     cin >> m;
  75.     vector<string> d(m);
  76.  
  77.     for(int i = 0; i < m; ++i){
  78.         cin >> d[i];
  79.         input[d[i]] = 1;
  80.     }
  81.  
  82.     for(auto el : v){
  83.         add(el);
  84.         if(input[el] == 1){;
  85.             input[el] = search(el) + 1;
  86.         }
  87.     }
  88.  
  89.     for(auto el : input){
  90.         if(input[el.first] == 1){
  91.             input[el.first] = cnt(el.first);
  92.         }
  93.     }
  94.  
  95.     for(int i = 0; i < m; ++i){
  96.         cout << input[d[i]] << '\n';
  97.     }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement