Advertisement
Guest User

Untitled

a guest
Apr 25th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5.  
  6. const int AlphabetLength = 26;
  7.  
  8. struct TrieNode
  9. {
  10. TrieNode *child[AlphabetLength];
  11. bool IsEnd;
  12. size_t height;
  13. };
  14.  
  15.  
  16. TrieNode* MakeNode()
  17. {
  18. TrieNode *newnode = new TrieNode;
  19. newnode->IsEnd = false;
  20. for (int i = 0; i < AlphabetLength; i++)
  21. {
  22. newnode->child[i] = NULL;
  23. }
  24. return newnode;
  25. }
  26.  
  27.  
  28. void add(TrieNode *root, string key)
  29. {
  30. TrieNode *current = root;
  31. for (size_t i = 0; i < key.length(); i++)
  32. {
  33. int letter = key[i] - 'a';
  34. if (!current->next[letter])
  35. {
  36. cout << key[i];
  37. current->next[letter] = MakeNode();
  38. current->next[letter]->height = current->height += 1;
  39. }
  40.  
  41. current = current->next[letter];
  42. }
  43. current->IsEnd = true;
  44. }
  45.  
  46.  
  47.  
  48. void compare(TrieNode *root, size_t key, int& more, int& less, int& equal)
  49. {
  50. for (int i = 0; i < AlphabetLength; i++) //Проходим по алфавиту
  51. {
  52. TrieNode* child = root->next[i];
  53. if (!child) continue; //Если встречаем NULL, то переходим к следующей букве
  54. if (child->IsEnd)
  55. {
  56. if (cur->Is_end && cur->height > key) more = more + 1;
  57. if (cur->Is_end && cur->height < key) less = less + 1;
  58. if (cur->Is_end && cur->height == key) equal = equal + 1;
  59. }
  60. compare(child); //рекурсивно вызываем функцию независимо от того, встретился ли конец слова.
  61. } //Это помогает избежать такого случая: если в дереве есть слова app и apple,
  62. //то он обработает оба, не потеряв конец слова apple
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement