Advertisement
ariful_lu

KOM Algorithm

Mar 23rd, 2019
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <string>
  4. #include <cstdio>
  5. using namespace std;
  6. void kmp(const string &needle, const string &haystack) {
  7.   int m = needle.size();
  8.   vector<int> border(m + 1);
  9.   border[0] = -1;
  10.   for (int i = 0; i < m; ++i) {
  11.     border[i+1] = border[i];
  12.     while (border[i+1] > -1 and needle[border[i+1]] != needle[i]) {
  13.       border[i+1] = border[border[i+1]];
  14.     }
  15.     border[i+1]++;
  16.   }
  17.  
  18.   int n = haystack.size();
  19.   int seen = 0;
  20.   for (int i = 0; i < n; ++i){
  21.     while (seen > -1 and needle[seen] != haystack[i]) {
  22.       seen = border[seen];
  23.     }
  24.     if (++seen == m) {
  25.       printf("%d\n", i - m + 1);
  26.         seen = border[m];
  27.     }
  28.   }
  29. }
  30.  
  31. int main(){
  32.   int m;
  33.   bool first = true;
  34.   while (scanf("%d",&m)==1) {
  35.     if (!first) puts("");
  36.     first = false;
  37.  
  38.     string needle; getline(cin, needle);
  39.     getline(cin, needle);
  40.     string haystack;
  41.     getline(cin, haystack);
  42.     kmp(needle, haystack);
  43.   }
  44.   return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement