Advertisement
Okorosso

KMP

Jun 4th, 2021
827
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <fstream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. std::vector<int> prefix_function(std::string s) {
  6.     using namespace std;
  7.     int n = s.length();
  8.     vector<int> p(n);
  9.     for (int i = 1; i < n; i++) {
  10.         int j = p[i - 1];
  11.         while (j > 0 && s[i] != s[j])
  12.             j = p[j - 1];
  13.         if (s[i] == s[j])
  14.             ++j;
  15.         p[i] = j;
  16.     }
  17.     return p;
  18. }
  19.  
  20. int main() {
  21.     using namespace std;
  22.     ifstream fin("input.txt");
  23.     ofstream fout("output.txt");
  24.     string mainStr, subStr;
  25.     getline(fin, mainStr);
  26.     getline(fin, subStr);
  27.  
  28.     string kmp_str = subStr + "#" + mainStr;
  29.     vector<int> prefix = prefix_function(kmp_str);
  30.     bool outed = false;
  31.     for (int i = 0; i < prefix.size(); i++) {
  32.         if (prefix[i] == subStr.size() and !outed) {
  33.             outed = true;
  34.             fout << i - 2 * subStr.size() + 1;
  35.             return 0;
  36.         }
  37.     }
  38.     fout << -1;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement