Advertisement
Alexvans

Trie

Aug 25th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define MAX 2000002
  4.  
  5. struct nodo{
  6.     int many;
  7.     int cubeta[26];
  8. };
  9.  
  10. nodo trie[MAX];
  11. int n,q,m=1,l;
  12. char palabra[MAX];
  13.  
  14. void meter(int l){
  15.     int pos=1;
  16.     for(int i=0; i<l; i++){
  17.         int letra=(palabra[i]-'a');
  18.         if(trie[pos].cubeta[letra]==0){
  19.             trie[pos].cubeta[letra]=++m;
  20.         }
  21.         pos=trie[pos].cubeta[letra];
  22.         trie[pos].many++;
  23.     }
  24. }
  25.  
  26. int prefix(int l){
  27.     int pos=1;
  28.     for(int i=0; i<l; i++){
  29.         int letra=(palabra[i]-'a');
  30.         if(trie[pos].cubeta[letra]==0){
  31.             return 0;
  32.         }
  33.         else
  34.             pos=trie[pos].cubeta[letra];
  35.     }
  36.     return trie[pos].many;
  37. }
  38.  
  39. int main(){
  40.     ios_base::sync_with_stdio(0);
  41.     cin.tie(0);
  42.     cin>>n;
  43.     for(int i=1;i<=n;i++){
  44.         cin>>palabra;
  45.         l=strlen(palabra);
  46.         meter(l);
  47.     }
  48.  
  49.     cin >> n;
  50.     for(int i=1;i<=n;i++){
  51.         cin>>palabra;
  52.         l=strlen(palabra);
  53.         cout << prefix(l) << '\n';
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement