Advertisement
Semior001

bor

Dec 10th, 2016
388
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 <cmath>
  3. #include <algorithm>
  4. #include <string>
  5. #include <vector>
  6. #include <cstdio>
  7. #include <map>
  8. #include <utility>
  9.  
  10. #include <queue>
  11. #include <stack>
  12. #include <cstring>
  13. #include <deque>
  14. #include <bitset>
  15. #include <cstdlib>
  16. #define F first
  17. #define S second
  18. #define mp make_pair
  19. #define pb push_back
  20. #define INF (1<<30)
  21. typedef long long ll;
  22. typedef long double ld;
  23.  
  24. using namespace std;
  25.  
  26. const int MAXN = 260;
  27.  
  28. struct vertex{
  29.     int next = -1;
  30.     bool ending = false;
  31. };
  32.  
  33. vertex root;
  34.  
  35. int sz = 1;
  36.  
  37. vertex bor[MAXN]['z'+1] = {root};
  38.  
  39. void add_string(const string s){
  40.     int v = 0;
  41.     int n = s.length();
  42.     int ch;
  43.     for(int i = 0; i < n; i++){
  44.         ch = s[i];
  45.         if(bor[v][ch].next==-1){
  46.             sz++;
  47.             bor[v][ch].next = sz - 1;
  48.         }
  49.         v = bor[v][ch].next;
  50.     }
  51.     bor[v][ch].ending = true;
  52. }
  53.  
  54. bool used[MAXN] = {false};
  55. int ans = 0;
  56.  
  57. void dfs(int v){
  58.     used[v] = true;
  59.     for(int ch = 'a'; ch <= 'z'; ch++){
  60.         if(bor[v][ch].ending){
  61.             ans++;
  62.         }
  63.         int to = bor[v][ch].next;
  64.         if(to!=-1 && !used[to]){
  65.             dfs(to);
  66.         }
  67.     }
  68. }
  69.  
  70. int find_prefix(const string s){
  71.     int n = s.length();
  72.     int v = 0;
  73.     int ch;
  74.     ans = 0;
  75.     for(int i = 0; i < n; i++){
  76.         ch = s[i];
  77.         if(bor[i][ch].next == -1){
  78.             return 0;
  79.         }
  80.         v = bor[v][ch].next;
  81.     }
  82.     dfs(v);
  83.     return ans;
  84. }
  85.  
  86. int main(){
  87.     int n;
  88.     cin >> n;
  89.     string s;
  90.     for(int i = 0; i < n; i++){
  91.         cin >> s;
  92.         add_string(s);
  93.     }
  94.  
  95.     int m;
  96.  
  97.     cin >> m;
  98.  
  99.     for(int i = 0; i < m; i++){
  100.         cin >> s;
  101.         cout << find_prefix(s) << endl;
  102.     }
  103.  
  104.     return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement