Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <vector>
- #include <iostream>
- #include <sstream>
- char index(char c, int k = 0) {
- return static_cast<char>(c - 'a' + k % 26);
- }
- std::string Shifted(std::string origin, int k) {
- std::vector<char> c(origin.size());
- for (int i = 0; i < origin.size(); ++i) {
- c[i] = 'a' + index(origin[i], k);
- }
- return std::string(c.begin(), c.end());
- }
- class Bohr {
- public:
- Bohr(): nodes(1) {
- }
- void Append(const std::string& s, int t) {
- int cur = 0;
- int i = 0;
- while (i < s.size() && nodes[cur].next[index(s[i])] != -1) {
- cur = nodes[cur].next[index(s[i])];
- ++i;
- }
- /// create new nodes
- while (i < s.size()) {
- nodes[cur].next[index(s[i])] = nodes.size();
- nodes.emplace_back();
- cur = nodes[cur].next[index(s[i])];
- ++i;
- }
- nodes[cur].terminal = t;
- }
- int Check(std::string x, int k) const {
- int cur = 0;
- int i = 0;
- auto s = Shifted(x, k);
- while (i < s.size() && nodes[cur].next[index(s[i])] != -1) {
- cur = nodes[cur].next[index(s[i])];
- ++i;
- }
- return i == s.size() ? nodes[cur].terminal : 0;
- }
- private:
- struct Node {
- int terminal;
- int next[26];
- Node(): terminal(0) {
- for (int i = 0; i < 26; ++i) {
- next[i] = -1;
- }
- }
- };
- std::vector<Node> nodes;
- };
- int main() {
- std::ios_base::sync_with_stdio(false);
- Bohr b;
- std::string line;
- std::getline(std::cin, line);
- std::istringstream iss(line);
- std::string s;
- while (iss >> s) {
- int t = 2 + ('z' - s[0]);
- s = Shifted(s, t);
- b.Append(s, t);
- }
- int q;
- std::cin >> q;
- for (int i = 0; i < q; ++i) {
- std::string s;
- std::cin >> s;
- int res;
- if ((res = b.Check(s, 2 + ('z' - s[0])), res != 0)) {
- std::cout << Shifted(s, 2 + ('z' - s[0]) + 26- res) << "\n";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement