MAGCARI

KMP

Jan 30th, 2023
803
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. /*
  2.     Task    : KMP
  3.     Author  : Phumipat C. [MAGCARI]
  4.     Language: C++
  5.     Created : 30 January 2023 [19:56]
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. char a[1010],b[1010];
  10. int prep[1010];
  11. int main(){
  12.     cin.tie(0)->sync_with_stdio(0);
  13.     cin.exceptions(cin.failbit);
  14.     cin >> a+1 >> b+1;
  15.     int lena = strlen(a+1),lenb = strlen(b+1);
  16.     int j=0;
  17.     for(int i=2;i<=lenb;i++){
  18.         while(j>0 && b[j+1] != b[i])    j = prep[j];
  19.         if(b[j+1] == b[i])  j++;
  20.         prep[i] = j;
  21.     }
  22.     j = 0;
  23.     for(int i=1;i<=lena;i++){
  24.         while(j>0 && b[j+1] != a[i])    j = prep[j];
  25.         if(b[j+1] == a[i])  j++;
  26.         if(j == lenb){
  27.             cout << "founded\n";
  28.             return 0;
  29.         }
  30.     }
  31.     cout << "not found\n";
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment