Advertisement
Dmaxiya

Solution of HihoCoder 1015: KMP

May 19th, 2018
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19.  
  20. #define LL long long
  21. const int maxn = 1000000 + 100;
  22. int T;
  23. int Next[maxn];
  24. char str1[maxn], str2[maxn];
  25.  
  26. void get_next(char *str) {
  27.     int j = 0;
  28.     for(int i = 2; str[i]; ++i) {
  29.         while(j != 0 && str[i] != str[j + 1]) {
  30.             j = Next[j];
  31.         }
  32.         if(str[i] == str[j + 1]) {
  33.             ++j;
  34.         }
  35.         Next[i] = j;
  36.     }
  37. }
  38.  
  39. int kmp(char *str1, char *str2) {
  40.     int j = 0;
  41.     int ret = 0;
  42.     for(int i = 1; str1[i]; ++i) {
  43.         while(j != 0 && str1[i] != str2[j + 1]) {
  44.             j = Next[j];
  45.         }
  46.         if(str1[i] == str2[j + 1]) {
  47.             ++j;
  48.         }
  49.         if(str2[j + 1] == '\0') {
  50.             j = Next[j];
  51.             ++ret;
  52.         }
  53.     }
  54.     return ret;
  55. }
  56.  
  57. int main() {
  58.     #ifdef LOCAL
  59.     freopen("test.txt", "r", stdin);
  60. //    freopen("out.txt", "w", stdout);
  61.     #endif // LOCAL
  62.     ios::sync_with_stdio(false);
  63.  
  64.     scanf("%d", &T);
  65.     while(T--) {
  66.         scanf("%s%s", str1 + 1, str2 + 1);
  67.         get_next(str1);
  68.         printf("%d\n", kmp(str2, str1));
  69.     }
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement