Advertisement
Guest User

KMP Optimized

a guest
Aug 25th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAXN 2000001
  3. using namespace std;
  4.  
  5. int fail[MAXN];
  6.  
  7. void failFunc(string &p){
  8.     int n = p.size();
  9.     fail[0] = -1;
  10.     for(int i = 0; i < n; i++){
  11.         int node = fail[i];
  12.         if(node >= 0 && p[node] != p[i]){
  13.             node = fail[node];
  14.         }
  15.         fail[i+1] = node+1;
  16.         if(p[i] == p[fail[i]]){
  17.             fail[i] = fail[fail[i]];
  18.         }
  19.     }
  20. }
  21.  
  22. void match(string &t, string &p){
  23.     int i = 0, j = 0;
  24.     while(i < (int) t.size()){
  25.         while(j >= 0 && p[j] != t[i]){
  26.             j = fail[j];
  27.         }
  28.         i++; j++;
  29.         if(j == (int) p.size()){
  30.             cout << i - p.size()  << endl;
  31.         }
  32.     }
  33. }
  34.  
  35. int n;
  36. string p,t;
  37.  
  38. int main(){
  39.     bool can = 0;
  40.     while(cin >> n){
  41.         if(can) cout << endl;
  42.         can = 1;
  43.         cin >> p >> t;
  44.         failFunc(p);
  45.         match(t,p);
  46.     }
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement