Advertisement
Rana_093

Trie Template(c++)

Oct 2nd, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define ll long long int
  6. #define db(x) cout<<#x<<" -> "<<x<<endl
  7.  
  8. struct node{
  9.     bool endmark;
  10.     node *next[10];
  11.     node(){
  12.         endmark = false;
  13.         for(int i=0; i<10; i++){
  14.             next[i] = 0;
  15.         }
  16.     }
  17. } *root ;
  18.  
  19. void _insert(string str){
  20.     node *cur = root;
  21.     for(int i=0; i<str.size(); i++){
  22.         int x = str[i]-'0';
  23.         if(cur->next[x]==0 ){
  24.             cur->next[x] = new node();
  25.         }
  26.         cur = cur->next[x];
  27.     }
  28.     cur->endmark = true;
  29. }
  30.  
  31. bool  _search(string str){
  32.     node *cur = root;
  33.     for(int i=0; i<str.size(); i++){
  34.         int x =  str[i]-'0';
  35.       //  db(x);
  36.        // db(cur->endmark);
  37.         if(cur->next[x] == 0 ){return false ;  }
  38.         cur = cur->next[x];
  39.         if(cur->endmark) {return true; }
  40.     }
  41.     return false;
  42. }
  43.  
  44. void del(node *cur){
  45.     for(int i=0; i<10; i++){
  46.         if(cur->next[i]){
  47.             del(cur->next[i]);
  48.         }
  49.     }
  50.     delete(cur);
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56.     ios_base::sync_with_stdio(false);
  57.     cin.tie(0);
  58.     int t;
  59.     cin>>t;
  60.     int tc  = 0;
  61.     while(t--){
  62.         root = new node();
  63.         string str;
  64.         int n;
  65.         cin>>n;
  66.         vector< string > vec;
  67.         bool f = false;
  68.         for(int i=0; i<n; i++){
  69.             cin>>str;
  70.             vec.push_back(str);
  71.            // cout<<endl;
  72.           //  if(_search(str)== true ){
  73.             //    f = true;
  74.             //  printf("Case %d: No\n",++tc);
  75.             // break;
  76.           //  }
  77.            // _insert(str);
  78.         }
  79.         sort(vec.begin(),vec.end());
  80.         for(int i=0; i<vec.size(); i++){
  81.             if(_search(vec[i]){ flag = true ; break; }
  82.             _insert(vec[i]);
  83.         }
  84.         del(root);
  85.         if(flag) {printf("Case %d: NO\n"); continue; }
  86.         printf("Case %d: YES\n",++tc);
  87.     }
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement