Advertisement
SkeptaProgrammer

Untitled

Dec 24th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1.  
  2. /*
  3. в 3-Е дереве найти все слова, содержащащие только указанные буквы
  4. */
  5.  
  6. #include "pch.h"
  7. #include <iostream>
  8. #include <string>
  9. #include <vector>
  10. using namespace std;
  11.  
  12. #define char_int(c) ((int)c - (int)'a')
  13. #define int_to_char(c) ((char)c + (char)'a')
  14. #define SIZE (26)
  15.  
  16.  
  17. struct Trie
  18. {
  19. Trie *child[SIZE];
  20. bool end;
  21. };
  22.  
  23. Trie *getNode()
  24. {
  25. Trie *newNode = new Trie;
  26. newNode->end = false;
  27. for (int i = 0; i < SIZE; i++)
  28. newNode->child[i] = NULL;
  29. return newNode;
  30. }
  31.  
  32. void insert(Trie *root, char *Key)
  33. {
  34. int n = strlen(Key);
  35. Trie *pChild = root;
  36.  
  37. for (int i = 0; i < n; i++)
  38. {
  39. int index = char_int(Key[i]);
  40.  
  41. if (!pChild->child[index])
  42. pChild->child[index] = getNode();
  43.  
  44. pChild = pChild->child[index];
  45. }
  46.  
  47. pChild->end = true;
  48. }
  49.  
  50. void searchWord(Trie *root, bool Hash[], string str)
  51. { if (root->end == true)
  52. cout << str << endl;
  53.  
  54. for (int K = 0; K < SIZE; K++)
  55. {
  56. if (Hash[K] == true && root->child[K])
  57. {
  58. char c = int_to_char(K);
  59. searchWord(root->child[K], Hash, str + c);
  60. }
  61. }
  62. }
  63.  
  64. void PrintAllWords(char Arr[], Trie *root, int n)
  65. {
  66. bool Hash[SIZE];
  67.  
  68. for (int i = 0; i < n; i++)
  69. Hash[char_int(Arr[i])] = true; // хранит символы, для которых нужно найти слова
  70.  
  71. Trie *pChild = root;
  72.  
  73. string str = "";
  74.  
  75. for (int i = 0; i < SIZE; i++)
  76. {
  77.  
  78. if (Hash[i] == true && pChild->child[i])
  79. {
  80. str = str + (char)int_to_char(i);
  81. searchWord(pChild->child[i], Hash, str);
  82. str = "";
  83. }
  84. }
  85. }
  86.  
  87.  
  88. int main()
  89. {
  90. char Dict[][20] = { "go", "bat", "me", "eat",
  91. "goal", "boy", "run"};
  92.  
  93. Trie *root = getNode();
  94. int n = sizeof(Dict) / sizeof(Dict[0]);
  95. for (int i = 0; i < n; i++)
  96. insert(root, Dict[i]);
  97. char arr[] = { 'e', 'o', 'b', 'a', 'm', 'g', 'l','h' };
  98. int N = sizeof(arr) / sizeof(arr[0]);
  99. PrintAllWords(arr, root, N);
  100. return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement