Advertisement
maxim_shlyahtin

Kmp_1

Aug 7th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. void form_suffix_array(std::vector<int>& pi, std::string& a) {
  6.     int j = 0, i = 1;
  7.     while (i < a.length()) {
  8.         if (a[i] != a[j]) {
  9.             if (j == 0 && pi[i] == 0) {
  10.                 ++i;
  11.             } else {
  12.                 j = pi[j - 1];
  13.             }
  14.         } else {
  15.             pi[i] = j + 1;
  16.             ++i;
  17.             ++j;
  18.         }
  19.     }
  20. }
  21.  
  22. std::vector<int> kmp(std::string& a, std::string& t, std::vector<int>& pi) {
  23.     std::vector<int> res;
  24.     int n = a.length();
  25.     int m = t.length();
  26.     int i = 0, j = 0;
  27.     while(i < n){
  28.         if (a[i] == t[j]) {
  29.             ++i; ++j;
  30.             if (j == m) {
  31.                 res.push_back(i - m);
  32.             }
  33.         } else {
  34.             if (j > 0) {
  35.                 j = pi[j - 1];
  36.             } else{
  37.                 ++i;
  38.             }
  39.         }
  40.     }
  41.     if (res.size() == 0) {
  42.         res.push_back(-1);
  43.     }
  44.     return res;
  45. }
  46.  
  47. int main() {
  48.     std::string p;
  49.     std::cin >> p;
  50.     std::string t;
  51.     std::cin >> t;
  52.     std::vector<int> pi(p.length(), 0);
  53.     form_suffix_array(pi, p);
  54.     std::vector<int> res = kmp(t, p, pi);
  55.     for (int i = 0; i < res.size(); ++i) {
  56.         if (i < res.size() - 1)
  57.             std::cout << res[i] << ',';
  58.         else
  59.             std::cout << res[i];
  60.     }
  61.     std::cout << '\n';
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement