Advertisement
_rashed

SPOJ DICT

Jul 11th, 2022
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #define ll long long
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. const int OO = 1e9;
  6. const double EPS = 1e-9;
  7.  
  8. string output = "";
  9.  
  10. class trie {
  11.     trie * c[26];
  12.     bool flag;
  13.  
  14.     public:
  15.     trie() {
  16.         memset(c,0,sizeof(c));
  17.         flag = 0;
  18.     }
  19.  
  20.     void add(string &s, int idx = 0) {
  21.         if(idx == s.size()) {
  22.             flag = 1;
  23.             return;
  24.         }
  25.         int curr = s[idx]-'a';
  26.         if(c[curr] == 0) {
  27.             c[curr] = new trie();
  28.         }
  29.         c[curr]->add(s,idx+1);
  30.     }
  31.  
  32.     bool printPrefix(string &s, int idx = 0, int oi = 0) {
  33.         bool ret = 0;
  34.         if(idx == s.size()) {
  35.             if(flag) {
  36.                 //cout << "here\n";
  37.                 //cout << "output is " << output << "\n";
  38.                 if(oi > 0) {
  39.                     cout << s << output.substr(0,oi) << "\n";
  40.                     ret = 1;
  41.                 }
  42.             }
  43.             for(int i = 0; i < 26; i++) {
  44.                 if(c[i]) {
  45.                     if(oi < output.length()) {
  46.                         output[oi] = (char) ('a'+i);
  47.                     }
  48.                     else {
  49.                         output += (char) ('a'+i);
  50.                     }
  51.                     ret |= c[i]->printPrefix(s,idx,oi+1);
  52.                 }
  53.             }
  54.         }
  55.         else {
  56.             int curr = s[idx]-'a';
  57.             if(c[curr] == 0) {
  58.                 return 0;
  59.             }
  60.             ret = c[curr]->printPrefix(s,idx+1,oi);
  61.         }
  62.         return ret;
  63.     }
  64. };
  65.  
  66. int main()
  67. {
  68.     ios_base::sync_with_stdio(false);
  69.     cin.tie(NULL);
  70.     cout.tie(NULL);
  71.     int n,k;
  72.     cin >> n;
  73.     trie dict;
  74.     for(int i = 0; i < n; i++) {
  75.         string s;
  76.         cin >> s;
  77.         dict.add(s);
  78.     }
  79.     cin >> k;
  80.     for(int ti = 1; ti <= k; ti++) {
  81.         cout << "Case #" << ti << ":\n";
  82.         string s;
  83.         cin >> s;
  84.         if(!dict.printPrefix(s)) {
  85.             cout << "No match.\n";
  86.         }
  87.     }
  88.     return 0;
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement