Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. // A C++ program that implements Z algorithm for pattern searching
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. void getZarr(string str, int Z[]);
  6.  
  7. // prints all occurrences of pattern in text using Z algo
  8. long search(string text)
  9. {
  10. long l = text.length();
  11. // Construct Z array
  12. int Z[l];
  13. getZarr(text, Z);
  14. long r=0;
  15. // now looping through Z array for matching condition
  16. for (long i = 1; i < l; ++i)
  17. {
  18.  
  19. r = r+Z[i];
  20. }
  21. return r;
  22. }
  23.  
  24. // Fills Z array for given string str[]
  25. void getZarr(string str, int Z[])
  26. {
  27. long n = str.length();
  28. long L, R, k;
  29.  
  30. // [L,R] make a window which matches with prefix of s
  31. L = R = 0;
  32. for (long i = 1; i < n; ++i)
  33. {
  34. // if i>R nothing matches so we will calculate.
  35. // Z[i] using naive way.
  36. if (i > R)
  37. {
  38. L = R = i;
  39.  
  40. // R-L = 0 in starting, so it will start
  41. // checking from 0'th index. For example,
  42. // for "ababab" and i = 1, the value of R
  43. // remains 0 and Z[i] becomes 0. For string
  44. // "aaaaaa" and i = 1, Z[i] and R become 5
  45. while (R<n && str[R-L] == str[R])
  46. R++;
  47. Z[i] = R-L;
  48. R--;
  49. }
  50. else
  51. {
  52. // k = i-L so k corresponds to number which
  53. // matches in [L,R] interval.
  54. k = i-L;
  55.  
  56. // if Z[k] is less than remaining interval
  57. // then Z[i] will be equal to Z[k].
  58. // For example, str = "ababab", i = 3, R = 5
  59. // and L = 2
  60. if (Z[k] < R-i+1)
  61. Z[i] = Z[k];
  62.  
  63. // For example str = "aaaaaa" and i = 2, R is 5,
  64. // L is 0
  65. else
  66. {
  67. // else start from R and check manually
  68. L = i;
  69. while (R<n && str[R-L] == str[R])
  70. R++;
  71. Z[i] = R-L;
  72. R--;
  73. }
  74. }
  75. }
  76. }
  77.  
  78. // Driver program
  79. int main()
  80. {
  81. int t;cin>>t;
  82. while(t--)
  83. {
  84. string s; cin>>s;
  85. long n = s.length();
  86. cout<<search(s)+n<<endl;
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement