Dang_Quan_10_Tin

LOOKUP (Trie)

Aug 10th, 2020 (edited)
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. /// --- from trieboi with love ---
  2. #include <iostream>
  3. #include <cstdio>
  4. #include <vector>
  5. #include <algorithm>
  6. #define task "LOOKUP"
  7. using namespace std;
  8. using ll = long long;
  9. using ld = long double;
  10.  
  11. const int N = 3e4 + 2;
  12. int n, q;
  13. const int Inf = 1e7;
  14.  
  15. struct Trie{
  16.     Trie *child[27];
  17.     vector<int> take;
  18.     int endhere;
  19.     Trie() {for(int i = 0; i < 27; ++i)child[i] = NULL;endhere = Inf;}
  20.     void Add(int id, string &s, int &v){
  21.         if(id == s.size()){
  22.             endhere = min(endhere, v);
  23.             take.push_back(v);
  24.             return;
  25.         }
  26.         if(!child[s[id] - 'a'])
  27.             child[s[id] - 'a'] = new Trie;
  28.         child[s[id] - 'a'] -> Add(id + 1, s, v);
  29.         take.push_back(v);
  30.     }
  31.     int first(int id, string &s){
  32.         if(id == s.size()){
  33.             return endhere;
  34.         }
  35.         if(!child[s[id] - 'a'])
  36.             return Inf;
  37.         return child[s[id] - 'a'] -> first(id + 1, s);
  38.     }
  39.     int count(int id, string &s, int &first){
  40.         int ans = upper_bound(take.begin(), take.end(), first) - take.begin();
  41.         if(id == s.size())
  42.             return ans;
  43.         if(!child[s[id] - 'a'])
  44.             return ans;
  45.         return child[s[id] - 'a'] -> count(id + 1, s, first) + ans;
  46.     }
  47. };
  48.  
  49. Trie beg;
  50.  
  51. void Read(){
  52.     cin >> n;
  53.     for(int i = 1; i <= n; ++i){
  54.         string s;
  55.         cin >> s;
  56.         beg.Add(0, s, i);
  57.     }
  58.     cin >> q;
  59. }
  60.  
  61. void Solve(){
  62.     string s;
  63.     cin >> s;
  64.     int first = beg.first(0, s);
  65.     //cerr << "first: " << first << "\n";
  66.     cout << beg.count(0, s, first)<< "\n";
  67. }
  68.  
  69. int32_t main(){
  70.     ios::sync_with_stdio(0);
  71.     cin.tie(0);
  72.     cout.tie(0); if(fopen(task".INP", "r"))
  73.     freopen(task".INP", "r", stdin),
  74.     freopen(task".OUT", "w", stdout);
  75.     Read();
  76.     while(q--)
  77.         Solve();
  78. }
  79.  
Add Comment
Please, Sign In to add comment