Advertisement
Fahim_7861

KMP Algorithm

Jun 21st, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef pair<ll,int>pp;
  5. #define sf(a) scanf("%d",&a)
  6. #define pf(a) printf("%d\n",a)
  7. #define mp make_pair
  8. #define pb push_back
  9. #define p pop_back
  10. #define ischar(x) (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z'))
  11. #define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL));
  12. #define mod 1000000007;
  13. #define MAX 100000
  14. int failure[MAX];
  15.  
  16. void failure_func(string pattern,int m)
  17. {
  18. ll i,j;
  19.  
  20. failure[0]=0;
  21. failure[1]=0;
  22.  
  23. for(i=2; i<=m; i++)
  24. {
  25. j=failure[i-1];
  26.  
  27. while(true)
  28. {
  29. if(pattern[j]==pattern[i-1])
  30. {
  31. failure[i]=j+1;
  32. break;
  33. }
  34.  
  35. if(j==0)
  36. {
  37. failure[i]=0;
  38. break;
  39. }
  40.  
  41. j=failure[j];
  42. }
  43. }
  44. }
  45.  
  46. bool kmp(string text, string pattern)
  47. {
  48. int n,m,i=0,j=0;
  49.  
  50. n=text.size();
  51. m=pattern.size();
  52.  
  53. failure_func(pattern,m);
  54.  
  55. while(true)
  56. {
  57. if(j==n)
  58. return false;
  59.  
  60. if(text[j]==pattern[i])
  61. {
  62. i++;
  63. j++;
  64.  
  65. if(i==m)
  66. {
  67. cout<<j-m<<endl;
  68. return true;
  69. }
  70. }
  71. else
  72. {
  73.  
  74. if(i==0)
  75. {
  76. j++;
  77. }
  78. else
  79. i=failure[i];
  80. }
  81. }
  82.  
  83. return false;
  84. }
  85.  
  86. int main()
  87. {
  88.  
  89. string t,p;
  90.  
  91. cin>>t>>p;
  92.  
  93.  
  94. cout<<kmp(t,p)<<endl;
  95.  
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement