Advertisement
coloriot

HA40_1

Jan 24th, 2025
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. class PrefixFunctionCalculator {
  6. private:
  7.     std::string s;
  8.     std::vector<int> pi;
  9.  
  10.     void computePrefixFunction() {
  11.         int n = s.size();
  12.         pi.resize(n, 0);
  13.  
  14.         for (int i = 1; i < n; i++) {
  15.             int j = pi[i - 1];
  16.             while (j > 0 && s[i] != s[j]) {
  17.                 j = pi[j - 1];
  18.             }
  19.             if (s[i] == s[j]) {
  20.                 j++;
  21.             }
  22.             pi[i] = j;
  23.         }
  24.     }
  25.  
  26. public:
  27.     explicit PrefixFunctionCalculator(const std::string &str)
  28.             : s(str)
  29.     {
  30.         computePrefixFunction();
  31.     }
  32.  
  33.     const std::vector<int>& getPrefixFunction() const {
  34.         return pi;
  35.     }
  36. };
  37.  
  38. int main() {
  39.     std::string input;
  40.     std::cin >> input;
  41.  
  42.     PrefixFunctionCalculator calculator(input);
  43.  
  44.     const std::vector<int>& prefixFunc = calculator.getPrefixFunction();
  45.  
  46.     for (size_t i = 0; i < prefixFunc.size(); ++i) {
  47.         std::cout << prefixFunc[i];
  48.         if (i + 1 < prefixFunc.size()) {
  49.             std::cout << ' ';
  50.         }
  51.     }
  52.     std::cout << std::endl;
  53.  
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement