bhupixb

Trie From Someone

Jan 29th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define F first
  3. #define S second
  4. #define PB push_back
  5. #define MP make_pair
  6.  
  7. using namespace std;
  8. typedef long long ll;
  9.  
  10. struct node {
  11. node *p[100];
  12. int count, leaf;
  13. node() {
  14. count = leaf = 0;
  15. memset(p, 0, sizeof(p));
  16. }
  17. };
  18.  
  19. class trie {
  20. node *root;
  21. public:
  22.  
  23. trie(){
  24. root = new node();
  25. }
  26.  
  27. void insert(string s){
  28. node *x = root;
  29. int length = s.length();
  30. for (int i = 0; i < length; i++) {
  31. if (x->p[s[i] - 'a'] == NULL) {
  32. x->p[s[i] - 'a'] = new node();
  33. }
  34. x = x->p[s[i] - 'a'];
  35. x->count++;
  36. }
  37. x->leaf++;
  38. }
  39.  
  40. void erase(string s){
  41. node *x = root;
  42. int length = s.length();
  43. for (int i = 0; i < length; i++) {
  44. x = x->p[s[i] - 'a'];
  45. x->count--;
  46. }
  47. x->leaf--;
  48. }
  49.  
  50. int find(string s){
  51. node *x = root;
  52. int length = s.length();
  53. for (int i = 0; i <length; ++i){
  54. if(x->p[s[i] - 'a'] == NULL){
  55. return 0;
  56. }
  57. x = x->p[s[i] - 'a'];
  58. }
  59. return (x->count - x->leaf);
  60. }
  61. };
  62.  
  63. int main() {
  64. ios::sync_with_stdio(0);
  65. cin.tie(0);
  66.  
  67. int n;
  68. cin >> n;
  69. vector<string> a(n);
  70. trie t;
  71. for (int i = 0; i < n; ++ i) {
  72. cin >> a[i];
  73. cout << t.find(a[i]) << "\n";
  74. t.insert(a[i]);
  75. }
  76. }
Add Comment
Please, Sign In to add comment