bhupixb

Number of prefixes Using Trie

Jan 29th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. // I can't tell you what it really is,
  2. // I can only tell you what it feels like.
  3. #include "bits/stdc++.h"
  4.  
  5. using namespace std;
  6.  
  7. //#define int long long
  8. #define F first
  9. #define S second
  10. #define rep(i,a,n) for (int i = a; i <= n; ++i)
  11. #define fo(i, n) for (int i = 1; i <= n; ++i)
  12. #define all(v) v.begin(), v.end()
  13. #define pb push_back
  14. #define P pair < int, int >
  15. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
  16.  
  17. const int N = 3e5 + 5;
  18. struct node {
  19. node *a[26];
  20. int len;
  21. int ed;
  22. node () {
  23. rep(i,0,25)
  24. a[i] = NULL;
  25. len = 0;
  26. ed = 0;
  27. }
  28. };
  29. string s;
  30. node *head = new node;
  31. void add(node *temp, int sz) {
  32. int i = 0;
  33. while(i != sz) {
  34. if(temp -> a[s[i] - 'a'] == NULL)
  35. temp -> a[s[i] - 'a'] = new node;
  36. temp = temp -> a[s[i] - 'a'];
  37. // cout << s[i];
  38. i += 1;
  39. }
  40. //cout << '\n';
  41. temp -> len += 1;
  42. }
  43. void pre(node *temp, node *par, string &str) {
  44. if(temp == NULL)
  45. return;
  46. for(int i = 0; i < 26; ++i) {
  47. if(temp -> a[i] != NULL) {
  48. // str += i + 'a';
  49. pre(temp -> a[i], temp, str);
  50. // cout << str << ' ';
  51. temp -> ed = temp -> a[i] -> len + temp -> a[i] -> ed;
  52. // cout << temp -> ed << ' ' << temp -> a[i] -> len << '\n';
  53. // str.pop_back();
  54. }
  55. }
  56. }
  57. /*5
  58. a
  59. aaaa
  60. aa
  61. aaa
  62. aaa
  63. */
  64. int ans = 0;
  65. void dp(node *temp, string &s, int idx) {
  66. if(temp == NULL || temp -> a[s[idx] - 'a'] == NULL) {
  67. return;
  68. }
  69. if(idx + 1 == s.size()) {
  70. // if(s == "aaa")
  71. // cout << temp -> ed << ' ' << temp -> a[idx] -> len << '\n';
  72. ans = temp -> ed - temp -> a[s[idx] - 'a'] -> len;
  73. return;
  74. }
  75. //cout << idx << ' ';
  76. //if(temp -> a[s[idx] - 'a'] != NULL)
  77. int let = s[idx] - 'a';
  78. // cout << let << ' ';
  79. dp(temp -> a[let], s, idx + 1);
  80. }
  81. signed main(){
  82. fast;
  83. int t;
  84. cin >> t;string str;
  85. std::vector<string> v;
  86. while(t--) {
  87. cin >> s;
  88. v.pb(s);
  89. add(head, (int)s.size());
  90. }
  91.  
  92. pre(head, head, str);
  93. for(auto i : v) {
  94. ans = 0;
  95. // cout << i << '\n';
  96. dp(head, i, 0);
  97. cout << ans << '\n';
  98. }
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114.  
  115.  
  116.  
  117.  
  118.  
  119. return 0;
  120. }
Add Comment
Please, Sign In to add comment