Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4. #include <queue>
  5. #include <string>
  6. using namespace std;
  7.  
  8. const int LEN = 1e6 + 9;
  9. const unordered_map <int, int> TMP;
  10.  
  11. int n;
  12. string str[LEN];
  13. string t;
  14.  
  15. vector <unordered_map<int, int>> bor;
  16. pair<int, char> par[LEN];
  17. int link[LEN];
  18. vector <int> rlink[LEN];
  19. vector <int> mark[LEN];
  20. int ok[LEN];
  21. int ANS[LEN];
  22.  
  23. void addInBor(string str, int m) {
  24. int v = 0;
  25.  
  26. for (int i = 0; i < str.size(); i++) {
  27. if (bor[v].count(str[i] - 'a') == 0) {
  28. bor.push_back(TMP);
  29. bor[v][str[i] - 'a'] = bor.size() - 1;
  30.  
  31. par[bor.size() - 1] = {v, str[i]};
  32.  
  33. v = bor.size() - 1;
  34. } else {
  35. v = bor[v][str[i] - 'a'];
  36. }
  37. }
  38.  
  39. mark[v].push_back(m);
  40. }
  41.  
  42. void dfs(int v) {
  43.  
  44. for (int u : rlink[v]) {
  45. dfs(u);
  46. }
  47.  
  48. for (int u : rlink[v]) {
  49. ok[v] += ok[u];
  50. }
  51. }
  52.  
  53. void dfs3(int v) {
  54. if (ok[v] > 0) {
  55. for (auto x : mark[v]) {
  56. ANS[x] = ok[v];
  57. }
  58. }
  59.  
  60. for (auto x : bor[v]) {
  61. dfs3(x.second);
  62. }
  63. }
  64.  
  65. int main() {
  66. freopen("search5.in", "r", stdin);
  67. freopen("search5.out", "w", stdout);
  68.  
  69. cin >> n;
  70.  
  71. par[0] = {0, '#'};
  72. bor.push_back(TMP);
  73. link[0] = 0;
  74.  
  75. for (int i = 0; i < n; i++) {
  76. cin >> str[i];
  77. addInBor(str[i], i);
  78. }
  79.  
  80. queue <int> q;
  81. q.push(0);
  82.  
  83. while (!q.empty()) {
  84. int v = q.front();
  85. q.pop();
  86.  
  87. for (auto u : bor[v]) {
  88. q.push(u.second);
  89. }
  90.  
  91. if (par[v].first == 0) {
  92. link[v] = 0;
  93. continue;
  94. }
  95.  
  96. int u = link[par[v].first];
  97. while (u != 0 && bor[u].count(par[v].second - 'a') == 0)
  98. u = link[u];
  99.  
  100. if (bor[u].count(par[v].second - 'a') == 0) {
  101. link[v] = 0;
  102. } else {
  103. link[v] = bor[u][par[v].second - 'a'];
  104. }
  105. }
  106.  
  107. cin >> t;
  108.  
  109. for (int i = 1; i < bor.size(); i++) {
  110. rlink[link[i]].push_back(i);
  111. }
  112.  
  113. int v = 0;
  114. for (int i = 0; i < t.size(); i++) {
  115. while (v != 0 && bor[v].count(t[i] - 'a') == 0)
  116. v = link[v];
  117.  
  118. if (bor[v].count(t[i] - 'a') == 0) {
  119. v = 0;
  120. } else {
  121. v = bor[v][t[i] - 'a'];
  122.  
  123. ok[v]++;
  124. }
  125. }
  126.  
  127. dfs(0);
  128.  
  129. dfs3(0);
  130.  
  131. for (int i = 0; i < n; i++) {
  132. cout << ANS[i] << "\n";
  133. }
  134.  
  135. return 0;
  136. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement