Advertisement
a_pramanik

kmp

Feb 21st, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. ///:-)
  2. #include <bits/stdc++.h>
  3. #define pb push_back
  4. #define ll long long int
  5. #define inf 2000000000
  6. #define sc(n) scanf("%d", &n)
  7. #define Aktaruzzaman using
  8. #define scl(n) scanf("%lld", &n)
  9. #define scd(n) scanf("%lf", &n)
  10. #define pi (2.0*acos(0.0))
  11. #define Pramanik namespace std;
  12. #define vsort(v)   sort(v.begin(),v.end())
  13. #define ull unsigned long long int
  14. #define mem(a, b) memset(a, b, sizeof a)
  15. #define cf 100009
  16. Aktaruzzaman Pramanik
  17.  
  18. string txt, pat;
  19. int lps[cf];
  20.  
  21. void buildLps()
  22. {
  23.     int M = pat.size();
  24.     lps[0]=0;
  25.     int j=0;
  26.     int i=1;
  27.     while(i<M)
  28.     {
  29.         if(pat[j]==pat[i]){
  30.             lps[i]=++j;
  31.             i++;
  32.         }
  33.         else{
  34.             if(j!=0)
  35.             {
  36.                 j = lps[j-1];
  37.             }
  38.             else{
  39.                 lps[i]=0;
  40.                 i++;
  41.             }
  42.         }
  43.     }
  44.  
  45. }
  46.  
  47. void kmp()
  48. {
  49.     buildLps();
  50.  
  51.     int M = pat.size();
  52.     int N = txt.size();
  53.     int i=0;
  54.     int j=0;
  55.     while(i<N)
  56.     {
  57.         if(txt[i]==pat[j])
  58.         {
  59.             i++;
  60.             j++;
  61.         }
  62.  
  63.         if(j==M)
  64.         {
  65.             printf("Found at position : %d\n", i-j);
  66.             j = lps[j-1];
  67.         }
  68.         else if(txt[i]!=pat[j])
  69.         {
  70.             if(j!=0)
  71.             {
  72.                 j = lps[j-1];
  73.             }
  74.             else{
  75.                 i++;
  76.             }
  77.         }
  78.  
  79.     }
  80.  
  81. }
  82.  
  83. int main()
  84. {
  85.     cout<<"Enter text : ";
  86.     cin>>txt;
  87.     cout<<"Enter pattern : ";
  88.     cin>>pat;
  89.     mem(lps, 0);
  90.     kmp();
  91.     buildLps();
  92.     for(int i=0; i<pat.size(); i++)printf("%d ",lps[i]);
  93.     printf("\n");
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement