fork(3) download
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. struct Node {
  9. char v;
  10. bool end;
  11. vector<Node*> next;
  12. };
  13.  
  14. Node *get_node(char v) {
  15. Node *node = new Node();
  16. node->v = v; node->end = false;
  17. node->next.resize(26);
  18. return node;
  19. }
  20.  
  21. void add(Node *h, string s, int idx) {
  22. if (s.size() == idx) {
  23. h->end = true;
  24. return;
  25. }
  26.  
  27. if (h->next[s[idx] - 'a'] == NULL) {
  28. h->next[s[idx] - 'a'] = get_node(s[idx]);
  29. }
  30.  
  31. add(h->next[s[idx] - 'a'], s, idx + 1);
  32. }
  33.  
  34. Node* pre(vector<string> d) {
  35. Node *h = get_node('$');
  36. for (string s : d) {
  37. add(h, s, 0);
  38. }
  39. return h;
  40. }
  41.  
  42. bool find(Node *h, string s, int idx) {
  43. if (idx == s.size()) return h->end;
  44. if (h->next[s[idx] - 'a'] != NULL) return find(h->next[s[idx] - 'a'], s, idx + 1);
  45. return false;
  46. }
  47.  
  48. int count(Node *base, Node *h, string s, int idx) {
  49. if (idx == s.size()) return h->end;
  50.  
  51. int res = 0;
  52. if (h->end) {
  53. res += count(base, base, s, idx);
  54. }
  55.  
  56. if (h->next[s[idx] - 'a'] != NULL) {
  57. res += count(base, h->next[s[idx] - 'a'], s, idx + 1);
  58. }
  59.  
  60. return res;
  61. }
  62.  
  63. int main() {
  64. vector<string> d(9);
  65. d[0] = "st";
  66. d[1] = "ck";
  67. d[2] = "cag";
  68. d[3] = "low";
  69. d[4] = "tc";
  70. d[5] = "rf";
  71. d[6] = "ove";
  72. d[7] = "a";
  73. d[8] = "sta";
  74.  
  75. Node *h = pre(d);
  76. cout << "Indexing done" << endl;
  77. string s;
  78. cin >> s;
  79. cout << count(h, h, s, 0) << endl;
  80. return 0;
  81. }
Success #stdin #stdout 0s 15240KB
stdin
stackoverflow
stdout
Indexing done
2