Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. struct elem
  4. {
  5. struct elem **arr;
  6. int pref;
  7. int x;
  8. }*t;
  9.  
  10. struct elem * buildtree()
  11. {
  12. t = (struct elem*)calloc(1, sizeof(struct elem));
  13. t->arr = (struct elem**)calloc(35, sizeof(struct elem*));
  14. t->x = 0;
  15. t->pref = 0;
  16. return t;
  17. }
  18.  
  19. int insert(struct elem* t, char *s)
  20. {
  21. int x = 0;
  22. if (!*s)
  23. {
  24. if (!t->x)
  25. {
  26. t->pref++;
  27. t->x++;
  28. return 1;
  29. }
  30. }
  31. else
  32. {
  33. x = s - 'a';
  34. if (!t->arr[x])
  35. t->arr[x] = buildtree();
  36. struct elem *temp = t->arr[x];
  37. if (insert(temp, s + 1))
  38. {
  39. t->pref++;
  40. return x + 1;
  41. }
  42.  
  43. }
  44. }
  45.  
  46. int delete(struct elem* t, char *s)
  47. {
  48. if (t)
  49. {
  50. if (*s != NULL)
  51. {
  52. int j = s - 'a';
  53. struct elem *temp = t->arr[j];
  54. if (delete(temp, s + 1))
  55. {
  56. t->pref--;
  57. return 1;
  58. }
  59. }
  60. else
  61. {
  62. if (t->x)
  63. {
  64. t->x--;
  65. t->pref--;
  66. return 1;
  67. }
  68. }
  69. }
  70. return 0;
  71. }
  72.  
  73. void check(char *command, char * w)
  74. {
  75. if (command[0] == 'I')
  76. {
  77. insert(t, w);
  78. return 0;
  79. }
  80. if (command[0] == 'P')
  81. {
  82. int res = pref(t, w);
  83. printf("%d", res);
  84. return 0;
  85. }
  86. if (command[0] == 'D')
  87. {
  88. delete(t, w);
  89. return 0;
  90. }
  91. }
  92.  
  93. int pref(struct elem* t, char *s)
  94. {
  95. int x = 0;
  96. if(t)
  97. {
  98. if( *s)
  99. {
  100. x = s - 'a';
  101. struct elem *temp = t->arr[x];
  102. return pref(temp, s + 1);
  103. }
  104. else
  105. return t->pref;
  106. }
  107. return 0;
  108. }
  109.  
  110. int main()
  111. {
  112. int n;
  113. scanf("%d", &n);
  114. t = buildtree();
  115. for (int i = 0; i < n; i++)
  116. {
  117. char *w = (char*)malloc(sizeof(char)*100100);
  118. char command[7];
  119. scanf("%s", command);
  120. scanf("%s", w);
  121. check(command, w);
  122. free(w);
  123. }
  124.  
  125. return 0;
  126. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement