Advertisement
Guest User

String Tale (KMP)

a guest
Aug 31st, 2016
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. typedef long long ll;
  4. using namespace std;
  5.  
  6. #define f(i,a,b) for(int i = (a); i <= (b); i++)
  7.  
  8. const ll MOD = 1000000007;
  9.  
  10. int F[250005], N;
  11. string S, T;
  12.  
  13. int main()
  14. {
  15.     cin >> N >> S >> T;
  16.     S += S;
  17.     F[0] = -1, F[1] = 0;
  18.     f(i,2,N)
  19.     {
  20.         int match = F[i-1];
  21.         while(match >= 0 && T[match] != T[i-1]) match = F[match];
  22.         F[i] = match+1;
  23.     }
  24.     int match = 0;
  25.     f(i,0,2*N-1)
  26.     {
  27.         while(match >= 0 && S[i] != T[match]) match = F[match];
  28.         match++;
  29.         if(match == N)
  30.         {
  31.             if(i == N-1) cout << 0;
  32.             else cout << 2*N-i-1;
  33.             return 0;
  34.         }
  35.     }
  36.     cout << -1;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement