Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <string>
  2. #include <vector>
  3. #include <iostream>
  4. #include <sstream>
  5.  
  6.  
  7.  
  8. char index(char c, int k = 0) {
  9.     return static_cast<char>(c - 'a' + k % 26);
  10. }
  11.  
  12. std::string Shifted(std::string origin, int k) {
  13.     std::vector<char> c(origin.size());
  14.     for (int i = 0; i < origin.size(); ++i) {
  15.         c[i] = 'a' + index(origin[i], k);
  16.     }
  17.     return std::string(c.begin(), c.end());
  18. }
  19.  
  20. class Bohr {
  21. public:
  22.     Bohr(): nodes(1) {
  23.  
  24.     }
  25.     void Append(const std::string& s, int t) {
  26.         int cur = 0;
  27.         int i = 0;
  28.         while (i < s.size() && nodes[cur].next[index(s[i])] != -1) {
  29.             cur = nodes[cur].next[index(s[i])];
  30.             ++i;
  31.         }
  32.         /// create new nodes
  33.         while (i < s.size()) {
  34.             nodes[cur].next[index(s[i])] = nodes.size();
  35.             nodes.emplace_back();
  36.  
  37.             cur = nodes[cur].next[index(s[i])];
  38.             ++i;
  39.         }
  40.         nodes[cur].terminal = t;
  41.     }
  42.     int Check(std::string x, int k) const {
  43.         int cur = 0;
  44.         int i = 0;
  45.         auto s = Shifted(x, k);
  46.         while (i < s.size() && nodes[cur].next[index(s[i])] != -1) {
  47.             cur = nodes[cur].next[index(s[i])];
  48.             ++i;
  49.         }
  50.         return i == s.size() ? nodes[cur].terminal : 0;
  51.     }
  52. private:
  53.     struct Node {
  54.         int terminal;
  55.         int next[26];
  56.         Node(): terminal(0) {
  57.             for (int i = 0; i < 26; ++i) {
  58.                 next[i] = -1;
  59.             }
  60.         }
  61.     };
  62.     std::vector<Node> nodes;
  63. };
  64.  
  65. int main() {
  66.     std::ios_base::sync_with_stdio(false);
  67.  
  68.     Bohr b;
  69.  
  70.     std::string line;
  71.     std::getline(std::cin, line);
  72.  
  73.     std::istringstream iss(line);
  74.     std::string s;
  75.     while (iss >> s) {
  76.         int t = 2 + ('z' - s[0]);
  77.         s = Shifted(s, t);
  78.         b.Append(s, t);
  79.     }
  80.     int q;
  81.     std::cin >> q;
  82.     for (int i = 0; i < q; ++i) {
  83.         std::string s;
  84.         std::cin >> s;
  85.         int res;
  86.         if ((res = b.Check(s, 2 + ('z' - s[0])), res != 0)) {
  87.             std::cout << Shifted(s, 2 + ('z' - s[0]) + 26- res) << "\n";
  88.         }
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement