bhupixb

Finding most frequent words from n words using trie

Jul 16th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. #define F first
  5. #define S second
  6.  
  7. // Struct for trie node (Memory Efficient)
  8. struct node {
  9. unordered_map < char, node* > mp;
  10. int cnt = 0;
  11. };
  12.  
  13. int ans = 0;
  14.  
  15. class trie {
  16. node *root;
  17. public:
  18. trie () {
  19. root = NULL;
  20. }
  21. void insert(const string &s) {
  22. if (root == NULL) {
  23. root = new node;
  24. }
  25. node *temp = root;
  26. for (auto i : s) {
  27. if (temp->mp.find(i) == temp->mp.end()) {
  28. temp->mp[i] = new node;
  29. }
  30. temp = temp->mp[i];
  31. }
  32. temp->cnt += 1;
  33. }
  34. void dfs(node *temp) {
  35. if (temp == NULL) {
  36. return;
  37. }
  38. for (auto i : temp->mp) {
  39. if (i.S != NULL) {
  40. ans = max(i.S->cnt, ans);
  41. dfs(i.S);
  42. }
  43. }
  44. }
  45. void Do() {
  46. dfs(root);
  47. }
  48. };
  49.  
  50. inline void solve() {
  51. int n;using namespace chrono;
  52. auto X = high_resolution_clock::now();
  53. string s;
  54. cin >> n;
  55. trie T;
  56. for (int i = 0; i < n; ++i) {
  57. cin >> s;
  58. T.insert(s);
  59. }
  60. T.Do();
  61.  
  62. auto Y = high_resolution_clock::now();
  63. // cout << setw(10) << "Estimated time = ";
  64. // cout << duration_cast<microseconds>(Y-X).count() / float(1e6) << "(uS)\n";
  65.  
  66. cout << ans;
  67. }
  68.  
  69. signed main() {
  70. ios_base::sync_with_stdio(0);
  71. cin.tie(NULL);
  72. cout.tie(NULL);
  73. int t = 1;
  74. //cin >> t; while(t--)
  75. solve();
  76. return 0;
  77. }
Add Comment
Please, Sign In to add comment