Tarango

TRIE Data Strcuture

Aug 25th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.27 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define Size 150005
  4.  
  5. class Trie {
  6.     int cnt;
  7.     Trie *child[52];
  8.  
  9. public:
  10.     Trie() {
  11.         cnt = 0;
  12.         for (int i = 0; i < 52; i++){
  13.             child[i] = NULL;
  14.         }
  15.     }
  16.  
  17.     void delete_trie() {
  18.         for (int i = 0; i < 52; i++)
  19.             if (child[i] != NULL) {
  20.                 child[i]->delete_trie();
  21.                 delete child[i];
  22.             }
  23.     }
  24.  
  25.     void insert_word(string &word, int pos) {
  26.         if (pos == (int)word.length()){
  27.             cnt++;
  28.             return;
  29.         }
  30.         int c;
  31.         if(word[pos] >= 'a') c = (int)(word[pos]-'a')+26;
  32.         else c = (int)(word[pos]-'A');
  33.         if (child[c] == NULL) {
  34.             child[c] = new Trie();
  35.         }
  36.         child[c]->insert_word(word, pos+1);
  37.     }
  38.  
  39.     int search_word(string &word, int pos) {
  40.         if (pos == (int)word.length()){
  41.             return cnt;
  42.         }
  43.         int c;
  44.         if(word[pos] >= 'a') c = (int)(word[pos]-'a')+26;
  45.         else c = (int)(word[pos]-'A');
  46.         if (child[c] == NULL) {
  47.             return 0;
  48.         }
  49.         return child[c]->search_word(word, pos+1);
  50.     }
  51. }*root;
  52.  
  53. int N,M,len;
  54.  
  55. int main() {
  56.     ios_base::sync_with_stdio(false);
  57.     cin.tie(NULL);
  58.     int nCase;
  59.     string s,st,ed,word;
  60.     cin >> nCase;
  61.     for (int cs = 1; cs <= nCase; cs++) {
  62.         cin >> N;
  63.         root = new Trie();
  64.         //Make the dictionary:
  65.         for (int i = 0; i < N; i++) {
  66.             cin >> s;
  67.             if(s.length()>2){
  68.                 sort(s.begin()+1,s.end()-1);
  69.             }
  70.             root->insert_word(s,0);
  71.         }
  72.         printf("Case %d:\n",cs);
  73.  
  74.         //Make sentence:
  75.         cin >> M;
  76.         int res = 1;
  77.         getline(cin,s);
  78.         for (int i = 0; i < M; i++) {
  79.             res = 1;
  80.             getline(cin,s);
  81.             stringstream ss(s);
  82.             while (ss >> word) {
  83.                 if(word.length() > 2){
  84.                     sort(word.begin()+1,word.end()-1);
  85.                 }
  86.                 int ret = root->search_word(word,0);
  87.                 res = res * ret;
  88.             }
  89.             printf("%d\n",res);
  90.         }
  91.         root->delete_trie();
  92.         delete root;
  93.     }
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment