Advertisement
farsid

KMP

Feb 23rd, 2020
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. /******************************************************************************
  2.  
  3.                               Online C++ Compiler.
  4.                Code, Compile, Run and Debug C++ program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8. // http://lightoj.com/volume_showproblem.php?problem=1255
  9.  
  10. #include <bits/stdc++.h>
  11.  
  12. using namespace std;
  13.  
  14. vector<int>F;
  15.  
  16. void preProcess(string s){
  17.     F.resize(s.size()+1);
  18.    
  19.     F[0] = 0;
  20.     F[1] = 0;
  21.    
  22.     int i = 0;
  23.     for(int len = 2;len <= s.size();len++){
  24.         while(i && s[len - 1] != s[i]){
  25.             i = F[i];
  26.         }
  27.         if( s[len - 1] == s[i]) {
  28.             i++;
  29.             F[len] = i;
  30.         } else {
  31.             F[i] = 0;
  32.         }
  33.     }
  34. }
  35.  
  36. int findMatchings(string text, string pattern) {
  37.     int cnt = 0;
  38.    
  39.     int j = 0;
  40.     for(int i=0;i<text.size();i++){
  41.         while(j && text[i] != pattern[j]){
  42.             j = F[j];
  43.         }
  44.         if(pattern[j] == text[i]){
  45.             j++;
  46.             if(j == pattern.size()){
  47.                 j = F[j];
  48.                 cnt++;
  49.             }
  50.         }
  51.     }
  52.    
  53.     return cnt;
  54. }
  55.  
  56. void init(){
  57.     F.clear();
  58. }
  59.  
  60. int main()
  61. {
  62.     int T, cas = 0;
  63.     scanf("%d",&T);
  64.    
  65.     while(T--){
  66.         string text;
  67.         string pattern;
  68.        
  69.         init();
  70.         cin>>text>>pattern;
  71.         preProcess(pattern);
  72.         printf("Case %d: %d\n",++cas,findMatchings(text,pattern));
  73.        
  74.     }
  75.  
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement