Tarango

TRIE

Sep 4th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. //TRIE Data Structure: Check if prefix exist.
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. #define Size 150005
  5.  
  6. class Trie {
  7.     bool found;
  8.     Trie *child[10];
  9.  
  10. public:
  11.     Trie() {
  12.         found = false;
  13.         for (int i = 0; i < 10; i++)
  14.             child[i] = NULL;
  15.     }
  16.     void delete_trie() {
  17.         for (int i = 0; i < 10; i++)
  18.             if (child[i] != NULL) {
  19.                 child[i]->delete_trie();
  20.                 delete child[i];
  21.             }
  22.     }
  23.     bool insert_word(string &word, int pos) {
  24.         if (found){
  25.             return false;
  26.         }
  27.         if (pos == (int)word.length()){
  28.             return found = true;
  29.         }
  30.         int c = (int)(word[pos] - '0');
  31.         if (child[c] == NULL) {
  32.             child[c] = new Trie();
  33.         }
  34.         return child[c]->insert_word(word, ++pos);
  35.     }
  36. }*root;
  37.  
  38. int N;
  39. string numbers[10005];
  40.  
  41. bool cmp(string a,string b){
  42.     if(a.length()<b.length()) return true;
  43.     if(a.length()>b.length()) return false;
  44.     if(a < b) return true;
  45.     return false;
  46. }
  47.  
  48. int main() {
  49.     int nCase;
  50.     cin >> nCase;
  51.     for (int cs = 1; cs <= nCase; cs++) {
  52.         cin >> N;
  53.         root = new Trie();
  54.         for (int i = 0; i < N; i++) {
  55.             cin >> numbers[i];
  56.         }
  57.         sort(numbers,numbers+N,cmp);
  58.         bool f = true;
  59.         for (int i = 0; i < N; i++) {
  60.             f = root->insert_word(numbers[i],0);
  61.             if(f == false) break;
  62.         }
  63.         if (f == true) {
  64.             printf("Case %d: YES\n",cs);
  65.         } else {
  66.             printf("Case %d: NO\n",cs);
  67.         }
  68.         root->delete_trie();
  69.         delete root;
  70.     }
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment