a53

pixeli

a53
Jun 6th, 2020
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. #include <fstream>
  2. #include <string>
  3. #include <map>
  4.  
  5. #define ALPHABET_SIZE 4
  6.  
  7.  
  8. std::ifstream fin ("pixeli.in");
  9. std::ofstream fout ("pixeli.out");
  10.  
  11. struct TrieNode {
  12. bool isEndOfWord;
  13. TrieNode* children[ALPHABET_SIZE];
  14.  
  15. TrieNode (): isEndOfWord (false) {
  16. for (int i = 0; i < ALPHABET_SIZE; ++ i)
  17. children[i] = nullptr;
  18. }
  19. };
  20.  
  21. TrieNode* root = new TrieNode ();
  22. int n, task, q;
  23. int64_t dim;
  24. std::string key;
  25. std::map <std::string, bool> Hash;
  26.  
  27.  
  28. inline bool isEmpty (TrieNode* root) {
  29. for (int i = 0; i < ALPHABET_SIZE; ++ i)
  30. if (root->children[i]) return false;
  31. return true;
  32. }
  33.  
  34. inline void Insert (std::string key) {
  35. TrieNode* pCrawl = root;
  36. for (int i = 0; i < (int)key.size (); ++ i) {
  37. int index = key[i] - '1';
  38. if (!pCrawl->children[index])
  39. pCrawl->children[index] = new TrieNode ();
  40. pCrawl = pCrawl->children[index];
  41. }
  42. pCrawl->isEndOfWord = true;
  43. }
  44.  
  45. inline int64_t Search (std::string key) {
  46. TrieNode* pCrawl = root;
  47. for (int i = 0; i < (int)key.size (); ++ i) {
  48. int index = key[i] - '1';
  49. if (!pCrawl->children[index]) {
  50. if (isEmpty (pCrawl)) return dim >> (2 * i);
  51. else return dim >> (2 * (i + 1));
  52. }
  53. pCrawl = pCrawl->children[index];
  54. }
  55. return 0;
  56. }
  57.  
  58. inline TrieNode* Remove (TrieNode* _root, std::string key, int depth = 0) {
  59. if (!_root) return nullptr;
  60.  
  61. if (depth == (int)key.size ()) {
  62. if (_root->isEndOfWord) _root->isEndOfWord = false;
  63. if (isEmpty (_root)) {
  64. delete _root; _root = nullptr;
  65. }
  66. return _root;
  67. }
  68.  
  69. int index = key[depth] - '1';
  70. _root->children[index] = Remove (_root->children[index], key, depth + 1);
  71.  
  72. if (isEmpty (_root) && !_root->isEndOfWord && _root != root) {
  73. delete _root; _root = nullptr;
  74. }
  75. return _root;
  76. }
  77.  
  78.  
  79. int main () {
  80. fin >> n >> q; dim = 1LL * n * n;
  81. for (int i = 1; i <= q; ++ i) {
  82. fin >> task >> key;
  83. if (task == 1) {
  84. if (!Hash[key]) Insert (key);
  85. else root = Remove (root, key);
  86. Hash[key] = !Hash[key];
  87. } else {
  88. if (!Hash[key]) fout << Search (key) << "\n";
  89. else fout << "0\n";
  90. }
  91. }
  92.  
  93. fin.close (), fout.close ();
  94. return 0;
  95. }
Add Comment
Please, Sign In to add comment